简体   繁体   中英

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 src/app/MyClass.java . The files I want to read are in res/filename.png , res/filename.xml .

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 input is null . What am I doing wrong? Any help would appreciated!

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.

单击完成后,您应该可以毫无问题地运行该文件。


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

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