簡體   English   中英

訪問文件與jar文件相鄰

[英]Access file adjacent to jar file

如何以最干凈的方式訪問jar文件(不在其內部)附近的文件?

我嘗試了各種組合,例如File configFile = new File("..//pinger.properties"); Pinger.class.getResourceAsStream("pinger.properties"); 但沒有讀取文件。

謝謝!

獲取您的jar文件的位置

考慮以下功能

public String path(String filename)
{
URL url1 = getClass().getResource("");
String ur=url1.toString();
ur=ur.substring(9);
String truepath[]=ur.split("myjar.jar!");
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0]+filename;
}//This method will work on Windows and Linux as well.
//You can alternatively use the following line to get the path of your jar file
//classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();

假設您的jar文件位於D:\\ Test \\ dist

然后path()將返回/ D:/ Test / dist / filename

您可以嘗試使用java.util.Properties類。

   Properties properties = new Properties();
   properties.load(getClass().getClassLoader().getResourceAsStream("pinger.properties"));

另一個樣本在這里

如何以最干凈的方式訪問jar文件(不在其內部)附近的文件?

添加一個清單文件,該清單文件使用相對路徑1引用依賴的Jar。 然后使用getResource(String)獲取資源的URL

  1. 有關詳細信息,請參見將類添加到JAR文件的類路徑中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM