Reputation: 484
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?
Upvotes: 0
Views: 245
Reputation: 58858
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
.
Upvotes: 1
Reputation: 4464
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.
Upvotes: 1