简体   繁体   English

在Eclipse的可运行jar文件中包含图片和声音文件

[英]Including pictures and sound files in a runnable jar file from Eclipse

I have many sound and picture files I am using in a pokemon game I'm writing with Eclipse. 我在用Eclipse编写的神奇宝贝游戏中使用了许多声音和图片文件。 Everything runs perfectly in Eclipse, but when I export it as a runnable jar, I get an error that the media is unavailable when I try running it. 一切都可以在Eclipse中完美运行,但是当我将其导出为可运行的jar时,出现错误消息:尝试运行它时媒体不可用。

This is the code I'm using for playing an mp3 file: 这是我用来播放mp3文件的代码:

    File file = new File("src/pokemon/mp3s/opening.mp3");
    final String mediaLocation = file.toURI().toURL().toExternalForm();
    Media media = new Media(mediaLocation);
    mp = new MediaPlayer(media);

After exporting as a runnable jar, I execute it with java -jar Pokemon2.jar and get this error message: 导出为可运行的jar后,我使用java -jar Pokemon2.jar执行它,并得到以下错误消息:

Exception in thread "Main" MediaException: MEDIA_UNAVAILABLE : C:\\Users\\Nick\\Desktop\\src\\pokemon\\mp3s\\opening.mp3 The system cannot find the path specified 线程“主”中的异常MediaException:MEDIA_UNAVAILABLE:C:\\ Users \\ Nick \\ Desktop \\ src \\ pokemon \\ mp3s \\ opening.mp3系统找不到指定的路径

How do I make my runnable jar be able to locate these additional resources? 如何使我的可运行jar能够找到这些其他资源?

Files in a jar are not accessible as regular files. Jar中的文件不能作为常规文件访问。 Instead you have to access them with getResource , which works when they are in the jar and out. 取而代之的是,您必须使用getResource访问它们,当它们在罐子里或外面时,它都可以工作。

getClass().getResource("/pokemon/mp3s/opening.mp3");

Deployed jar file doesn't contains source files or src folder. 部署的jar文件不包含源文件或src文件夹。 It is your IDE which make source files compiled and put them at other place, (eg in netbeans inside build\\classes). 这是您的IDE,用于编译源文件并将其放置在其他位置(例如,在build \\ classes中的netbeans中)。 And when you deploy your project it is your mp3 file will be present inside that jar file, not in src folder. 当您部署项目时,您的mp3文件将存在于该jar文件中,而不是src文件夹中。

You should try another approach. 您应该尝试另一种方法。
suppose your file is present in src/pokemon/mp3s/opening.mp3 假设您的文件位于src / pokemon / mp3s / opening.mp3中
and a class is present in src/pokemon/Referer.java 并且src / pokemon / Referer.java中存在一个类

Now you can access your mp3 file by taking Referer class as reference : 现在,您可以将Referer类作为参考来访问mp3文件:

URL fileUrl = Referer.class.getResource("mp3s/opening.mp3");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM