Accessing resources inside a JAR [duplicate]

2019-09-18 08:25发布

This question already has an answer here:

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.

2条回答
Luminary・发光体
2楼-- · 2019-09-18 08:39

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")
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-18 08:52

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().

查看更多
登录 后发表回答