Unable to load xml file from a absolute path

后端 未结 2 1204
-上瘾入骨i
-上瘾入骨i 2020-12-22 02:04

There is a maven project A. Once I do mvn clean install, the project builds and the jar is available at my local repository ie c:\\repository\\com\\stackoverflow\\A\\A.jar<

2条回答
  •  感情败类
    2020-12-22 02:35

    If the A class (that is bundled in your A.jar) wants to load the xml from the jar and it tries to access it in the way shown in your first code example then it does not access p.xml inside your jar. It accesses the file at that location.

    It is easy to test if this is your case. After your jar is created, temporarily delete p.xml from the file system and run A class. It will fail to load it.

    When a class needs to load a resource that is bundled in a jar then it does not use File but the classloader.

    From the names you provide, I assume that your class A is in package: com.stackoverflow.A The xml file is in the package com.stackoverflow.A.res

    All the approaches below will load a stream with your xml

    InputStream is = null;
    
    // Using class - relative to the class location because path does not start with "/"
    is = SimpleWriter.class.getResourceAsStream("res/p.xml");
    
    // Using class - absolute path because path starts with "/"
    is = SimpleWriter.class.getResourceAsStream("/com/stackoverflow/A/res/p.xml");
    
    // Using classloader - path is *always* absolute. Note that leading "/" is missing
    is = SimpleWriter.class.getClassLoader().getResourceAsStream("com/stackoverflow/A/res/p.xml");
    

提交回复
热议问题