问题
I've made a project consisting of some java files, an images folder with a few images and a data folder with a few text files. Everything works perfectly when I compile the program and run it through terminal. I decided to try and turn it into a jar file, so after lots of research I managed to do it, including using a manifest file. Here is what I type into terminal to do it:
jar cvfm Program.jar manifest.txt *.class images data
Giving this output:
added manifest
adding: a.class (in = 500) (out = 500) (deflated 50%)
adding: b.class (in = 500) (out = 500) (deflated 50%)
adding: images/ (in = 0) (out = 0) (stored 0%)
adding: images/a.png (in = 500) (out = 500) (deflated 50%)
adding: images/b.png (in = 500) (out = 500) (deflated 50%)
adding: data/ (in = 0) (out = 0) (stored 0%)
adding: data/a.txt (in = 500) (out = 500) (deflated 50%)
The only lines of which stand out being the images/ and data/ which have in, out, stored =0.
This works and it lists all of the files correctly within the jar file. The jar file even runs perfectly when in the correct directory of the program, however if I remove it from that directory, it no longer can find any of the resource files (images and data) and I have no idea why. It may be a way that I am referencing them in my code or that the resource files aren't attached properly, but I'm not really sure. My manifest file consists of:
Manifest-Version: 1.0
Main-Class: Strike
Any help would be appreciated.
回答1:
If your resource files (images, etc ...) are stored in the jar file, you should access them with
inputstream = getClass()
.getClassLoader()
.getResourceAsStream("Path to your file in the jar file");
回答2:
You have a classpath problem. When you launch the JAR in your project directory, in fact you are reading resources from the filesystem, not from the archive.
To read resources from the classpath use Class.getResourceAsStream(String)
InputStream in = getClass().getResourceAsStream("/images/foo.png");
And put foo.png
inside an images
directory in the final archive like you already do. Note the leading slash in /images/foo.png
. Quoting the doc
An absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where themodified_package_name
is the package name of this object with '/' substituted for '.' ('\u002e').
If you don't want to use an IDE to build your project, there are tools like Ant and Maven.
来源:https://stackoverflow.com/questions/12090882/trouble-turning-java-project-into-jar-file