溫馨提示×

java怎么獲取配置文件參數

小億
182
2023-09-28 17:28:34
欄目: 編程語言

在Java中,可以使用java.util.Properties類來讀取配置文件中的參數。以下是一個簡單的示例:

首先,創建一個名為config.properties的配置文件,并在文件中添加以下內容:

name=John Doe
age=30

然后,在Java代碼中使用Properties類讀取配置文件中的參數:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
Properties properties = new Properties();
FileInputStream configFile = null;
try {
configFile = new FileInputStream("config.properties");
properties.load(configFile);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (configFile != null) {
try {
configFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String name = properties.getProperty("name");
int age = Integer.parseInt(properties.getProperty("age"));
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

運行上述代碼,將輸出以下結果:

Name: John Doe
Age: 30

上述代碼中,首先創建了一個Properties對象properties,然后使用FileInputStream來讀取配置文件config.properties。接著,使用properties.load(configFile)方法加載配置文件中的參數。最后,使用getProperty方法根據參數名獲取相應的值。使用Integer.parseInt將字符串類型的年齡轉換為整數類型。

注意:在使用FileInputStream讀取配置文件時,需要提供配置文件的路徑。上述示例假設配置文件與Java代碼位于同一目錄下,如果不是,請提供正確的路徑。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女