溫馨提示×

java中properties配置文件怎么使用

小億
106
2023-09-17 00:54:33
欄目: 編程語言

在Java中,可以使用java.util.Properties類來讀取和使用配置文件。

首先,創建一個Properties對象并加載配置文件??梢允褂?code>Properties的load()方法來加載配置文件,傳入一個InputStream對象作為參數。例如,假設配置文件名為config.properties,可以使用以下代碼加載該配置文件:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
// 使用配置文件中的屬性值
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
}

然后,可以使用Properties對象的getProperty()方法根據配置文件中的鍵獲取對應的值。

配置文件config.properties的內容如下:

username=admin
password=123456

運行上述代碼,將輸出:

Username: admin
Password: 123456

這樣你就可以在Java程序中使用配置文件中的屬性值了。

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