简体   繁体   English

如何将jar文件与参考文件一起打包?

[英]How to package a jar file along with reference files?

Using eclipse, exporting a runnable jar file is pretty simple when I'm only using the application on my computer. 当我仅在计算机上使用应用程序时,使用eclipse导出可运行的jar文件非常简单。 Any files that the program is using (sprite sheets, audio tracks, etc.) only exist on my computer, so sending solely the jar to another machine won't work. 该程序正在使用的所有文件(子画面,音轨等)仅存在于我的计算机上,因此仅将jar发送到另一台机器将不起作用。

What is the easiest way to package a jar along with all the necessary files so that I could run the program on any machine? 将jar和所有必需的文件打包在一起,以便可以在任何计算机上运行程序的最简单方法是什么?

I see from your tags that you are working in Eclipse. 我从您的标签中看到您正在使用Eclipse。 I am not sure if this method will work in other IDEs and I don't think it'll work at all if you're doing everything manually (it relies on the compiler automatically copying resources over to the bin folder. 我不确定该方法是否可以在其他IDE中使用,如果您手动进行所有操作,则我认为它根本不起作用(它依赖于编译器自动将资源复制到bin文件夹中。

The simplest way (at least what I use) is to define another sourcefolder (I like res ). 最简单的方法(至少是我使用的方法)是定义另一个源文件夹(我喜欢res )。

Then you can just add packages to this source folder and dump the relevant images. 然后,您可以将软件包添加到此源文件夹并转储相关的映像。 Then rebuild your project. 然后重建您的项目。

Finally, you can use getClass().getResourceAsStream("package/path/file_name.whatever"); 最后,您可以使用getClass().getResourceAsStream("package/path/file_name.whatever"); to get your files. 获取您的文件。

After an export as jar , it should work, even on other machines. 导出为jar之后,即使在其他计算机上也可以工作。

If you don't require the other files to be actual files on the file system (which means you can't use File , FileInputStream , etc ) then you can use the resource system. 如果您不要求其他文件是文件系统上的实际文件(这意味着您不能使用FileFileInputStream ),则可以使用资源系统。 If you put them inside the JAR, you can access them like this: 如果将它们放在JAR中,则可以这样访问它们:

InputStream fileStream = SomeClassInYourJarFile.class
                                            .getResourceAsStream("/path/to/file.png");

This example would give you an InputStream reading from the /path/to/file.png entry in your JAR file - that is, the "file.png" file inside a folder "to" inside a folder "path". 此示例将为您提供一个InputStream从JAR文件中的/path/to/file.png条目中读取-即,文件夹“ path”中的“ to”文件夹中的“ file.png”文件。

This does not require the files to be in a JAR file - it can load them from wherever your .class files are stored, JAR or not. 不需要文件位于JAR文件中-它可以从存储.class文件的位置(无论是否存在JAR)加载它们。 If you put them in your source folder, Eclipse will automatically copy them to that place - so the above line would also work if you had a package path.to containing a file called file.png . 如果你把它们放在你的源文件夹,Eclipse会自动将它们复制到那个地方-因此上面的线也将工作,如果你有一个包path.to包含一个名为file.png

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

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