可能な限りクリーンな方法でjarファイルに隣接するファイルにアクセスするにはどうすればよいですか?jarファイルに隣接するファイルにアクセスする
File configFile = new File("..//pinger.properties");
とPinger.class.getResourceAsStream("pinger.properties");
のようなさまざまな組み合わせを試しましたが、ファイルが読み取られていません。
ありがとうございます!
可能な限りクリーンな方法でjarファイルに隣接するファイルにアクセスするにはどうすればよいですか?jarファイルに隣接するファイルにアクセスする
File configFile = new File("..//pinger.properties");
とPinger.class.getResourceAsStream("pinger.properties");
のようなさまざまな組み合わせを試しましたが、ファイルが読み取られていません。
ありがとうございます!
java.util.Propertiesクラスを使用できます。
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("pinger.properties"));
別のサンプルがhereです。
可能な限りクリーンな方法でjarファイルに隣接するファイルにアクセスするにはどうすればよいですか?
相対パスを使用して、依存Jarを参照するマニフェストファイルを追加します。次にgetResource(String)
を使用して、リソースにURL
を取得します。
あなたの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であると仮定します\テスト\のdistの
その後のパス()/D:/ Test/dist/filename
を返します。