Accessing resources within a JAR file

一个人想着一个人 提交于 2019-12-11 18:44:11

问题


I'm trying to access resources that I have embedded in a JAR file. The class that needs to access a file is:

/worldEntities/factories/RoomFactory.class

and it tries to access:

/map-data/roomDescriptions.xml

To do this, I have added the following code to RoomFactory.class:

Document doc = docBuilder.parse(this.getClass().getResourceAsStream("/map-data" + File.separator + "roomDescriptions.xml"));

When I execute the project in NetBeans, it works fine with no errors. However, when I attempt to run the code from the command line, by entering

java -jar Program.jar

I get a java.lang.IllegalArgumentException: InputStream cannot be null, and it points the code that I describe above.

Thanks in advance for any help,

Thomas


回答1:


  1. Name with "-" char are not valid Java package name. So "map-data" is not a valid package name.

  2. Then File.separator could be different on different platforms. Use "/" in your code to be sure to use the valid package separator.




回答2:


You need to make sure you bundle the resource with the .jar, otherwise it won't be found

This post should help on how to do it from NetBeans



来源:https://stackoverflow.com/questions/10153790/accessing-resources-within-a-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!