简体   繁体   中英

Accessing resource file in jar

I am making a maven java project in eclipse. Now I am required to make a executable jar by command line by maven. while my code is executing resource file, it works fine but in some scenario it does not work. My code structure is as follow :

Directory Structure :

src/main/java : A.java
src/main/resources : file1.properties

class A {
 private static final String TEMPLATE_LOCATION= "src/main/resources/";

 public static void main() {
      Properties props = new Properties();
      props.load(new FileInputStream(TEMPLATE_LOCATION + "file1.properties"));
 }
}

pom.xml : 
   <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
   </resources> 

I am making jar file by : mvn package
jar file structure :

target/jarFileName.jar
target/classes :
    com/A.class
    file1.properties

contents in jar :
  com/A.class
  file1.properties

command to execute :
cd myProjectRootDirectory
java -jar target/jarFileName.jar, it works fine

But when i execute from target folder like :
cd target
java -jar jarFileName.jar , does not work, Error : src/main/resources/file1.properties not found.

I changed code by props.load(new props.load(FileInputStream(A.class.getClassLoader().getResource("file1.properties").getPath()))); then also does not work.
But in eclipse it works fine.

Any can suggest me, where i am doing mistake

You should use getResourceAsStream function and you already specified the resource folder main/resources at your pom don't use this at your implementatition. This function will get any file in the classpath. FileInputStream will search the file as starting from the current working directory. So it is not safe(wrong use) when you reading the file in the jar file.

Thread.currentThread().getContextClassLoader().getResourceAsStream(...)

public static Properties loadFile(String fileName) throws IOException {
    Properties props = new Properties();
    InputStream inputStream = null;


    inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);


    props.load(inputStream);

    return props;
}

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