資源從它們的類路徑根進行解釋。而你的情況,當你運行你的程序是這樣的:
java -cp etc/application.properties:./lib/properties-loader-0.0.1-SNAPSHOT.jar
根是
./etc/application.properties
./lib/properties-loader-0.0.1-SNAPSHOT.jar
均未包含您application.properties文件(如一個子資源)。如果修改您的命令是這樣的:
然後你可以看你的財產在你的程序文件如:
Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
作爲一個側面說明,它總是最好使用在classpath完全合格的路徑設置。
*編輯*
這是一個工作的例子,應該說明資源加載:
mkdir props; cd props
mkdir etc; touch etc/application.properties
mkdir test; vi test/PropLoader.java
該內容到編輯器中粘貼然後保存:
package test;
import java.io.InputStream;
public class PropLoader {
public static void main(String[] args) {
try {
final String path;
if(args.length == 1) path = args[0].trim();
else path = "etc/application.properties";
final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if(is == null) throw new RuntimeException("Failed to load " + path + " as a resource");
else System.out.printf("Loaded resource from path: %s\n", path);
} catch(Exception e) {
e.printStackTrace();
}
}
}
並測試:
javac test/PropLoader.java
java -cp . test.PropLoader
產量是Loaded resource from path: etc/application.properties
。
@drhirsch我認爲在這種情況下,標籤'maven-assembly-plugin'標籤可能比'assemblies'更合適。 – oschrenk 2012-02-28 18:48:11
當然,把它改成你認爲合適的東西 - 但是像以前一樣,「組裝」是錯誤的。事實上,正是這個標籤,是我帶來的 - 它是關於機器碼的。每個標籤都有一個描述 - 如果您不確定,請閱讀它。 – hirschhornsalz 2012-02-28 18:52:31
忘記我可以自己改變它。謝謝你的提示。 – oschrenk 2012-02-28 18:56:54