[英]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.