[英]Load external resource into classpath when running JAR
我有一個需要在啟動時進行配置的應用程序。 但是,我不能將其存儲在 /resources 中,因為托管此應用程序的每個環境都將完全不同。 我想把它放在通過環境中定義的系統屬性找到的目錄下,但現在我想讓絕對路徑工作 - 比如說/tr/apps/myFile.txt (其中 /tr/apps/ 是根應用程序的部署位置)。
I found a Maven plugin which looked like it would do the job: https://maven.apache.org/surefire/maven-surefire-plugin/examples/configuring-classpath.html
所以我把這個添加到我的 pom 中:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>/tr/apps</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
</plugin>
</plugins>
</build>
現在我必須使用以下方法來獲取文件:
InputStream inputStream = Thread.currentThread().getContextClassloader().getResourceAsStream("tr/apps/myFile.txt")
if(inputStream == null) {
throw new Exception("myFile.txt not found");
}
這個異常似乎總是被拋出(即它無法在類路徑中找到文件)。 有人知道這是為什么嗎? 或者是否有替代插件/解決方案?
非常感謝任何輸入!
您是否嘗試在 Stackoverflow 中尋找答案? 這是 Java 中的一個常見問題,答案總是很簡單(最終取決於您是否使用 spring)。
嘗試使用此處描述的解決方案JAR 文件如何讀取外部屬性文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.