问题
I'm trying to play an audio file. In my IDE (intellij) that works completely fine, but when running in a JAR, I get the error 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)
The file's location inside the JAR is audio/click.au
, and the JAR is located at D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar
which afaik should make the absolute path D:\soni801\Documents\Redsea Productions\The Great X Wars\alpha-0.0.7.1.jar\audio\click.au
, however the system can't find a file at this location? What's happening here?
This is the code in my AudioPlayer.java
file:
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath() /*+ "/res"*/ + filePath).getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
Alternatively, you can find the entire file, as well as the rest of the project, on the GitHub repository
All help is appreciated.
I am aware that this might be a duplicate of other questions, but unfortunately other solutions didn't solve my problem
If the question is unclear, comment any improvements I could make, and I will edit the question
回答1:
The AudioSystem.getAudioInputStream
method is overloaded and can accept a File
, a URL
or an InputStream
as an argument. Of these, URL
is usually the best choice.
It's advantage over File
is that a URL
can address a file within a jar, which a File
cannot do.
It's advantage over InputStream
is that additional conditions are imposed: the audio file must support mark
and reset
methods. My experience with audio files is that it's kind of hit or miss as to whether this will be possible or not. I confess I don't know the specifics as to why.
To obtain a URL from your jar, the simplest form it perhaps the following:
URL url = this.getClass().getResource("yourAudioFileName");
This assumes that the audio resource is in the same package as the class "this". Subfolders of the package can be addressed as well, this way. But I don't think the symbol "../" can be counted on to obtain a resource from a parent folder.
Alternatively, instead of 'this' you can specify a class in the package or parent package of the audio resource. Also, you can prefix the address with a "/". In this last case, e.g., this.getClass().getResource("/yourAudioFileName")
, the root source folder of the project is the starting point for the address rather than the package holding 'this'.
来源:https://stackoverflow.com/questions/63020106/the-system-cannot-find-the-path-specified-in-jar