cress cress - 1 year ago 99
Java Question

Java/JavaFX, read files from inside project and jar file

I have some images and xml files inside my project folders which I want to read. For example, my code is inside

. The files I want to read are in

So if I wanted to give my project an icon, I would do this (works fine if running through Eclipse):

primaryStage.getIcons().add(new Image("file:res/icon.png"));

The problem with this is that when I run it through the .jar file, the image does not appear. Same thing with other files. It can't find the xml file through the jar file.

I tried this:

InputStream input = getClass().getResourceAsStream("res/icon.png");
primaryStage.getIcons().add(new Image(input));

But Eclipse says that
. What am I doing wrong? Any help would appreciated!

Answer Source

There are some possibilities as to why this is the case. The first of which is you are running a JAR and not an Executable Jar File. Another possible reason why the program fails to display images is that when exporting you are not clicking the extract required libraries button as shown below. If neither of these are the case comment below.

Once you click finish you should be able to run the file with no issue.

Try creating a source folder named resources (right click project > New > Source Folder) and put everything in there. You can now do getClass().getResourceAsStream("/file.ext") and it shouldn't be null.

If there are any other errors after you create your jar file (following the picture above), you can run this through command line/terminal and it should show you any errors you may have:

java -jar jarfile.jar
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download