简体   繁体   中英

file not found exception in jar

public class ABC {
    public ABC() {
        File file = new File("xyz.xml");

but when I run my jar as follows:

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?

If you need to read file content in JARs, you can not use File class directly. Using ClassLoader to load it:

// for example read the SeleniumConfiguration.xml in the default package

InputStream input = SeleniumConfiguration.class.getResourceAsStream("/SeleniumConfiguration.xml");

The NullPointerException is a clear indication that the file was not found.

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.

Normally you can use the InputStream as suggested, but incase you want to do further non-java operations on the file eg 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.

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:

jar-file

  • com
  • META-INF
  • Element.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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