Javaでプロパティファイルを読み込む方法
Javaでは、プロパティファイルの読み込みにはjava.util.Propertiesクラスを使用できます。
プロパティファイルを読み込む手順は以下のとおりです。
- 性格
Properties properties = new Properties();
- ロードする
try {
FileInputStream fileInputStream = new FileInputStream("path/to/your/file.properties");
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
- getProパティ()
String value = properties.getProperty("key");
完全なサンプルコードは:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ReadPropertyFile {
public static void main(String[] args) {
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream("path/to/your/file.properties");
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
String value = properties.getProperty("key");
System.out.println(value);
}
}
必ず”path/to/your/file.properties”を実際のプロパティファイルパスに置き換えてください。