file not found exception in jar

前端 未结 4 1236
逝去的感伤
逝去的感伤 2020-12-10 06:07
public class ABC {
    public ABC() {
        File file = new File(\"xyz.xml\");

but when I run my jar as follows:

java -jar filena         


        
相关标签:
4条回答
  • 2020-12-10 06:33

    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");
    
    0 讨论(0)
  • 2020-12-10 06:33

    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
    0 讨论(0)
  • 2020-12-10 06:43

    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.

    0 讨论(0)
  • 2020-12-10 06:49

    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.

    0 讨论(0)
提交回复
热议问题