简体   繁体   中英

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

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?

I see from your tags that you are working in 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.

The simplest way (at least what I use) is to define another sourcefolder (I like 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"); to get your files.

After an export as jar , it should work, even on other machines.

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. If you put them inside the JAR, you can access them like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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