问题
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:
Name with
"-"char are not valid Java package name. So"map-data"is not a valid package name.Then
File.separatorcould 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