访问JAR内部的资源 [英] Accessing resources inside a JAR

查看:125
本文介绍了访问JAR内部的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为罐子中的资源加载编写测试程序,但是遇到了问题.

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

我读到您应该使用ClassLoadergetClass()来访问jar中的文件.由于我用于加载资源的方法是静态的,因此我使用ClassLoader.getSystemResource(String path). 我的程序找到了文件,但说该路径包含文件名或目录名的无效语法.这是我用来加载资源的代码:

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

是的,我正在为OpenAL加载声音文件.

Yes, I'm loading soundfiles for OpenAL.

无论如何,我应该提醒您,它实际上找到了文件,但是路径语法无效.这是我以jar形式运行它时获得的路径的示例:

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:

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

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

我试图删除!"而且我仍然遇到相同的错误.如果我删除文件:",则找不到该文件.请注意,当我在Eclipse中运行时,该程序运行良好.

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.

推荐答案

如果要从jar中获取文件,请使用getResourceAsStream()并将软件包名称用作路径.

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")

这篇关于访问JAR内部的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆