Accessing resources inside a JAR [duplicate]

2019-09-18 07:45发布

问题:

This question already has an answer here:

  • How do I read a resource file from a Java jar file? 9 answers

I'm making a test program for resource loading inside a jar and I'm having problems.

I've read that you should use ClassLoader or alternatively getClass() to access a file inside a jar. Since the method that i use to load the resource is static, I use ClassLoader.getSystemResource(String path). My program finds the file but says that the path contains invalid syntax for filenames or directory names. This is the code that I use to load my resources:

String path = ClassLoader.getSystemResource(file).getPath();

System.out.println(path);

try {
    wave = WaveData.create(new BufferedInputStream(new FileInputStream(path)));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

AL10.alBufferData(buffers.get(i), wave.format, wave.data, wave.samplerate);
wave.dispose();

Yes, I'm loading soundfiles for OpenAL.

Anyway, I should remind you that it actually finds the file but the path has invalid syntaxing. This is an example of the path I get when I run it in jar form:

file:\C:\Users\name\development\jars\test.jar!\sounds\test.wav

I've tried to remove the "!" and I still get the same error. If i remove the "file:" it doesn't find the file. Note that the program runs fine when I'm running in Eclipse.

回答1:

If you are getting a file from a jar use getResourceAsStream() and use the package names for the path.

getResourceAsStream("/com/project/resources/sounds/myfile.wav")


回答2:

Not every URL corresponds to a file in file system. In particular, a particular entry in a JAR file isn't itself a file, and hence cannot be read with a FileInputStream. You can open an InputStream for a class path resource using Class.getResourceAsStream() or ClassLoader.getResourceAsStream().