简体   繁体   English

访问JAR文件中的资源

[英]Accessing resources within a JAR file

I'm trying to access resources that I have embedded in a JAR file. 我正在尝试访问嵌入在JAR文件中的资源。 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: 为此,我向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. 当我在NetBeans中执行项目时,它运行正常,没有错误。 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. 我得到一个java.lang.IllegalArgumentException:InputStream不能为null,它指向我上面描述的代码。

Thanks in advance for any help, 预先感谢您的帮助,

Thomas 汤玛士

You need to make sure you bundle the resource with the .jar, otherwise it won't be found 您需要确保将资源与.jar捆绑在一起,否则将找不到该资源

This post should help on how to do it from NetBeans 这篇文章应该对如何从NetBeans做到这一点有所帮助

  1. Name with "-" char are not valid Java package name. 带有"-"字符的名称不是有效的Java包名称。 So "map-data" is not a valid package name. 因此, "map-data"不是有效的软件包名称。

  2. Then File.separator could be different on different platforms. 然后, File.separator在不同平台上可能会有所不同。 Use "/" in your code to be sure to use the valid package separator. 在代码中使用"/" ,以确保使用有效的包分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM