在jar中访问资源文件

时间:2014-05-22 06:22:14

标签: java hibernate

我正在eclipse中创建一个maven java项目。现在我需要通过maven命令行创建一个可执行jar。 虽然我的代码正在执行资源文件,但它工作正常但在某些情况下它不起作用。 我的代码结构如下:

目录结构:

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

1 个答案:

答案 0 :(得分:0)

你应该使用getResourceAsStream函数,你已经在你的pom中指定了资源文件夹main / resources,而不是在你的实现中使用它。此函数将获取类路径中的任何文件。 FileInputStream将从当前工作目录开始搜索文件。因此,当您在jar文件中读取文件时,它是不安全的(错误使用)。

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;
}