繁体   English   中英

访问jar中的资源文件

[英]Accessing resource file in jar

我在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

您应该使用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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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