Java の Properties クラスを使用する方法
Javaでは、Propertiesクラスを使用してプロパティファイルを読み込む・書き出すことができます。以下はPropertiesクラスを使用する一例です。
- Propertiesオブジェクトを作成し、プロパティファイルを読み込みます。
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream("config.properties");
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
- 属性値の取得
String value = properties.getProperty("key");
System.out.println(value);
- プロパティを設定する:
properties.setProperty("key", "value");
- プロパティファイルを保存:
try {
FileOutputStream fileOutputStream = new FileOutputStream("config.properties");
properties.store(fileOutputStream, "Config Properties");
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
プロパティファイルの読み書きを行ううえでPropertiesクラスを使用した基本手順以上です。プロパティファイルの形式はキーと値のペア(”key=value”)で、各プロパティは1行です。