java 在 jar 中找不到文件异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4755806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
file not found exception in jar
提问by swarup7m
public class ABC {
public ABC() {
File file = new File("xyz.xml");
but when I run my jar as follows:
但是当我按如下方式运行我的 jar 时:
java -jar filename.jar arguments....
then it is showing error:
然后它显示错误:
java.lang.IllegalArgumentException: InputStream cannot be null
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:120)
at com.ensarm.niidle.web.proxy.ABC.<init>(ABC.java:47)
How can I fix it?
我该如何解决?
回答by qrtt1
If you need to read file content in JARs, you can not use File class directly. Using ClassLoader to load it:
如果需要读取 JAR 中的文件内容,则不能直接使用 File 类。使用 ClassLoader 加载它:
// for example read the SeleniumConfiguration.xml in the default package
// 例如读取默认包中的 SeleniumConfiguration.xml
InputStream input = SeleniumConfiguration.class.getResourceAsStream("/SeleniumConfiguration.xml");
回答by Thilo
The NullPointerException is a clear indication that the file was not found.
NullPointerException 明确表示未找到该文件。
InputStream input=ABC.class.getResourceAsStream("/Element.xml");
InputStream input=ABC.class.getResourceAsStream("/Element.xml");
Where is your XML file? If you place it in the same package (directory inside the jar file) as ABC.class, then it should be Element.xml
without the leading slash.
你的 XML 文件在哪里?如果将它放在与 ABC.class 相同的包(jar 文件内的目录)中,那么它应该Element.xml
没有前导斜杠。
回答by Johnydep
Normally you can use the InputStream as suggested, but incase you want to do further non-java operations on the file e.g decrypting it using external application etc, you can use FileOutputStream to write this stream into a file and then use it's path as a correct file path. In simple words, you can unjar this file to your file system.
通常,您可以按照建议使用 InputStream,但如果您想对文件进行进一步的非 Java 操作,例如使用外部应用程序等对其进行解密,您可以使用 FileOutputStream 将此流写入文件,然后使用它的路径作为正确的文件路径。简而言之,您可以将此文件解压缩到您的文件系统。
回答by Hao
Did you put your xml file at the root of the jar file? If you use path like "/Element.xml", the jar file structure should be like:
你把你的xml文件放在jar文件的根目录了吗?如果你使用像“/Element.xml”这样的路径,jar文件结构应该是这样的:
jar-file
jar 文件
- com
- META-INF
- Element.xml
- 电脑
- 元信息
- 元素.xml