在罐子里加载资源文件 [英] Loading resource files within a jar

查看:59
本文介绍了在罐子里加载资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

加载资源(声音,图像,xml数据)的最佳方法是什么,这种方法也可以在分布式jar文件中使用?

What's the best way to load resources (Sounds, images, xml data), that also works from inside a distributed jar file?

我需要加载一些声音,图像和xml数据,以便在我的程序中使用.使用

I need to load some sounds, images, and xml data, for use in my program. Using

AudioInputStream ais = AudioSystem.getAudioInputStream(new File("~/src/com/example/package/name/assets/TestSound.wav"));

由于明显的原因而不能在jar中工作,包括src不会在jar中的事实.

does not work in the jar, for obvious reasons, including the fact that src will not be in the jar.

(正在工作的)MWE: http://pastebin.com/CNq6zgPw

(A working) MWE: http://pastebin.com/CNq6zgPw

推荐答案

此代码段对我有用:

Clip clip = null;
ClassLoader cl = this.getClass().getClassLoader();
AudioInputStream ais;
URL url = cl.getResource("com/example/project/assets/TestSound.wav");
System.out.println(url);
try {
    ais = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(ais);
}
catch (Exception e) {
    e.printStackTrace();
    System.exit(1);
}

重要的是不要将/src/文件夹添加到类路径中.

The important thing is not adding the /src/ folder to the class path.

关键更改是将cl.getResource("/com/example/project/assets/TestSound.wav")更改为cl.getResource("com/example/project/assets/TestSound.wav"); 因为/com/...表示该路径是绝对路径,而com/...表示该路径是相对路径.

The critical change is changing cl.getResource("/com/example/project/assets/TestSound.wav") to cl.getResource("com/example/project/assets/TestSound.wav"); because /com/... indicates that the path is absolute, whereas com/... indicates that the path is relative.

例如

System.out.println(new File("/Test.File").getAbsolutePath());
System.out.println(new File("Test.File").getAbsolutePath());

返回

/Test.File
/Users/alphadelta/Documents/Workspace/TestProject/Test.File

分别.

创建的第一个文件是使用"/Test.File"创建的,这是绝对的.第二个是使用"Test.File"创建的,它相对于eclipse中的项目根目录.

The first File created is created using "/Test.File", which is absolute. The second is created using "Test.File", which is relative to the project root in eclipse.

这篇关于在罐子里加载资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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