系统找不到JAR中指定的路径
The system cannot find the path specified in JAR
我正在尝试播放音频文件。在我的 IDE (intellij) 中工作得很好,但是当在 JAR 中 运行 时,我得到错误 java.io.FileNotFoundException: D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar\audio\click.au (The system cannot find the path specified)
文件在 JAR 中的位置是 audio/click.au
,JAR 位于 D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar
,afaik 应该是绝对路径 D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar\audio\click.au
,但是系统找不到文件在这个位置?这里发生了什么?
这是我的 AudioPlayer.java
文件中的代码:
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath() /*+ "/res"*/ + filePath).getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
或者,您可以在 GitHub repository
上找到整个文件以及项目的其余部分
感谢所有帮助。
我知道这可能与其他问题重复,但不幸的是其他解决方案没有解决我的问题
如果问题不清楚,评论我可以做的任何改进,我会编辑问题
AudioSystem.getAudioInputStream
方法已重载,可以接受 File
、URL
或 InputStream
作为参数。其中,URL
通常是最佳选择。
它优于 File
的是 URL
可以在 jar 中寻址文件,而 File
则不能。
它优于 InputStream
的地方在于附加了条件:音频文件必须支持 mark
和 reset
方法。我对音频文件的经验是,这是否可能是一种偶然。我承认我不知道具体原因。
要从您的 jar 中获取 URL,最简单的形式可能如下所示:
URL url = this.getClass().getResource("yourAudioFileName");
这假定音频资源与 class“this”在同一个包中。包的子文件夹也可以通过这种方式寻址。但我不认为符号“../”可以指望从父文件夹中获取资源。
或者,您可以在音频资源的包或父包中指定 class 而不是 'this'。此外,您可以在地址前加上“/”。在最后一种情况下,例如 this.getClass().getResource("/yourAudioFileName")
,项目的根源文件夹是地址的起点,而不是包含 'this'.
的包
我正在尝试播放音频文件。在我的 IDE (intellij) 中工作得很好,但是当在 JAR 中 运行 时,我得到错误 java.io.FileNotFoundException: D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar\audio\click.au (The system cannot find the path specified)
文件在 JAR 中的位置是 audio/click.au
,JAR 位于 D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar
,afaik 应该是绝对路径 D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar\audio\click.au
,但是系统找不到文件在这个位置?这里发生了什么?
这是我的 AudioPlayer.java
文件中的代码:
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath() /*+ "/res"*/ + filePath).getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
或者,您可以在 GitHub repository
上找到整个文件以及项目的其余部分感谢所有帮助。
我知道这可能与其他问题重复,但不幸的是其他解决方案没有解决我的问题
如果问题不清楚,评论我可以做的任何改进,我会编辑问题
AudioSystem.getAudioInputStream
方法已重载,可以接受 File
、URL
或 InputStream
作为参数。其中,URL
通常是最佳选择。
它优于 File
的是 URL
可以在 jar 中寻址文件,而 File
则不能。
它优于 InputStream
的地方在于附加了条件:音频文件必须支持 mark
和 reset
方法。我对音频文件的经验是,这是否可能是一种偶然。我承认我不知道具体原因。
要从您的 jar 中获取 URL,最简单的形式可能如下所示:
URL url = this.getClass().getResource("yourAudioFileName");
这假定音频资源与 class“this”在同一个包中。包的子文件夹也可以通过这种方式寻址。但我不认为符号“../”可以指望从父文件夹中获取资源。
或者,您可以在音频资源的包或父包中指定 class 而不是 'this'。此外,您可以在地址前加上“/”。在最后一种情况下,例如 this.getClass().getResource("/yourAudioFileName")
,项目的根源文件夹是地址的起点,而不是包含 'this'.