Runnable JARs missing Images/Files (Resources)

2019-01-01 05:40发布

When I export my code as runnable JAR from eclipse all the files that I've set it to grab such as button images and other files are missing even though they are actually in the JAR. I've added getClass().getResource in front of the files but then when I try to run the JAR nothing even happens, any suggestions?

标签: java eclipse jar
5条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 06:20

The path needs to be right for the resource.

For "foo.gif" being at the root of the jar, you must refer to it using "/foo.gif".

If the program works correctly after a complete clean and rebuild, but fails as a jar, you most likely do not have the files included in the jar.

查看更多
春风洒进眼中
3楼-- · 2019-01-01 06:29

You need to get the images using stream like this - this.class.getClassLoader().getResourceAsStream("test.jpg") and make sure the images are present in the jar which you are referencing.

查看更多
何处买醉
4楼-- · 2019-01-01 06:31

Try to put the folders in the jar the same way that you got them in the program. Put in the same resources in the same places that you have them in the project. The jar will reference to them the same way as in your compiler did.

查看更多
萌妹纸的霸气范
5楼-- · 2019-01-01 06:39

Seems like you not putting your stuff in the right sense. In order to make it work, follow these steps :

  1. Right-Click your Project in Project Explorer Tree.
  2. Go to New -> Source Folder and then provide any Name to the Source Folder.
  3. Now manually add your stuff to this Source Folder so created by you, like if you want to add images then make a New Folder, by manually visiting this Source Folder through File System.
  4. Name this New Folder as images and copy your images to this Folder.
  5. Now go back to your Eclipse IDE and Refresh your Project from the Project Explorer, by Right Clicking your Project, here you be able to see your added content now after refreshing.

Now in order to access, say any image, you will use.

getClass().getResource("/images/yourImageName.extension");

which will return one URL object. Do remember the first forward slash, in this case, since whatever is inside your Source Folder is accessed with the help of this, in simpler terms. Now when you will Run your project, the content of this Source Folder will be automatically added to the bin folder and when you will create a Runnable Jar, then the stuff inside your Source Folder can be accessed as it is.

查看更多
残风、尘缘若梦
6楼-- · 2019-01-01 06:43

As nIcE cOw said, you just need to create a Source Folder in you Project Explorer Tree. All the files inside that folder will be in the root project folder.

To refer to them, you must write your projects name slash the file name as it:

getClass().getResource("ProjectName/image.extension");

I hope this helps!

查看更多
登录 后发表回答