実行用にすべてのコードをアーカイブした JAR ファイルがあります。実行する前に変更/編集する必要があるプロパティ ファイルにアクセスする必要があります。プロパティ ファイルを JAR ファイルと同じディレクトリに保存したいのですが、Java にそのディレクトリからプロパティ ファイルを取得するように指示する方法はありますか?
注: プロパティ ファイルをホーム ディレクトリに保持したり、コマンド ライン引数でプロパティ ファイルのパスを渡したりすることは望ましくありません。
ベストアンサー1
.properties
したがって、メイン/実行可能 jar と同じフォルダーにあるファイルを、メイン/実行可能 jar のリソースとしてではなく、ファイルとして扱う必要があります。その場合、私の独自の解決策は次のとおりです。
まず最初に、プログラム ファイルのアーキテクチャは次のようになります (メイン プログラムが main.jar で、メイン プロパティ ファイルが main.properties であると仮定します)。
./ - the root of your program
|__ main.jar
|__ main.properties
このアーキテクチャでは、main.jar は単なるテキストベースのファイルなので、main.jar の実行前または実行中に (プログラムの現在の状態に応じて) 任意のテキスト エディターを使用して main.properties ファイル内の任意のプロパティを変更できます。たとえば、main.properties ファイルには次の内容が含まれる場合があります。
app.version=1.0.0.0
app.name=Hello
したがって、メイン プログラムをルート/ベース フォルダーから実行すると、通常は次のように実行されます。
java -jar ./main.jar
または、すぐに:
java -jar main.jar
main.jar では、main.properties ファイルにあるすべてのプロパティに対していくつかのユーティリティ メソッドを作成する必要があります。プロパティには次のようなメソッドapp.version
があるとします。getAppVersion()
/**
* Gets the app.version property value from
* the ./main.properties file of the base folder
*
* @return app.version string
* @throws IOException
*/
import java.util.Properties;
public static String getAppVersion() throws IOException{
String versionString = null;
//to load application's properties, we use this class
Properties mainProperties = new Properties();
FileInputStream file;
//the base folder is ./, the root of the main.properties file
String path = "./main.properties";
//load the file handle for main.properties
file = new FileInputStream(path);
//load all the properties from this file
mainProperties.load(file);
//we have loaded the properties, so close the file handle
file.close();
//retrieve the property we are intrested, the app.version
versionString = mainProperties.getProperty("app.version");
return versionString;
}
メイン プログラムの任意の部分でapp.version
値が必要な場合は、次のようにメソッドを呼び出します。
String version = null;
try{
version = getAppVersion();
}
catch (IOException ioe){
ioe.printStackTrace();
}