Javaで設定ファイルを読み込む方法は何ですか?
Javaにおける設定ファイルの読み込み方法は主に以下のいくつかがあります:
- 性質
- 特性
- 読み込む
- getProperty() メソッド
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigLoader {
public static void main(String[] args) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("config.properties"));
String value = properties.getProperty("key");
System.out.println("Value: " + value);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- クラスローダー
- クラスローダー
- リソースを取得するためのgetStream()
- 特性
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigLoader {
public static void main(String[] args) {
Properties properties = new Properties();
try (InputStream inputStream = ConfigLoader.class.getClassLoader().getResourceAsStream("config.properties")) {
properties.load(inputStream);
String value = properties.getProperty("key");
System.out.println("Value: " + value);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- リソースバンドル
- リソースバンドル
- プロパティ
import java.util.ResourceBundle;
public class ConfigLoader {
public static void main(String[] args) {
ResourceBundle resourceBundle = ResourceBundle.getBundle("config");
String value = resourceBundle.getString("key");
System.out.println("Value: " + value);
}
}
どの方法を使用しても、設定ファイルをクラスパスに配置するか、設定ファイルの絶対パスを指定する必要があります。例では設定ファイルの名前はconfig.propertiesですが、必要に応じて変更できます。