Java 言語を使って config ディレクトリ内の設定ファイルを読み込むにはどうしたらいいでしょうか。
JavaのPropertiesクラスを使えば、configディレクトリの構成ファイルを読み取ることができます。
config.properties という名前の設定ファイルの入力ストリームを取得するには、最初にクラスローダを使用して設定ファイルを取得する必要があります。以下のコードを使用して、入力ストリームを取得できます。
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");
次に、Properties クラスを使って入力ストリームをロードし、config ファイルの内容を読み取れます
Properties properties = new Properties();
properties.load(inputStream);
プロパティオブジェクトは設定ファイルの内容を読み込んでいますので、getProperty()メソッドにて設定項目の値を取得することができます。
String configValue = properties.getProperty("config.key");
config.key は設定のキー値です。
完全なコード例:
import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
try {
// 获取配置文件的输入流
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.properties");
// 加载配置文件
Properties properties = new Properties();
properties.load(inputStream);
// 读取配置项的值
String configValue = properties.getProperty("config.key");
System.out.println("配置项的值是:" + configValue);
// 关闭输入流
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
設定ファイルconfig.propertiesがconfigディレクトリ下にあり、クラスパスからアクセスできるようになっていることを確認してください。