溫馨提示×

Java怎么讀寫Properties配置文件

小億
87
2024-01-19 18:15:23
欄目: 編程語言

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

讀取配置文件:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            // 加載配置文件
            FileInputStream fileInputStream = new FileInputStream("config.properties");
            properties.load(fileInputStream);
            fileInputStream.close();

            // 讀取配置項
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");

            System.out.println("Username: " + username);
            System.out.println("Password: " + password);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

寫入配置文件:

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            // 設置配置項
            properties.setProperty("username", "admin");
            properties.setProperty("password", "123456");

            // 保存配置文件
            FileOutputStream fileOutputStream = new FileOutputStream("config.properties");
            properties.store(fileOutputStream, null);
            fileOutputStream.close();

            System.out.println("Config file saved successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述示例中,假設配置文件名為config.properties,內容如下:

username=admin
password=123456

讀取配置文件時,使用Properties類的load方法加載文件流,并使用getProperty方法獲取配置項的值。

寫入配置文件時,使用Properties類的setProperty方法設置配置項的值,并使用store方法保存到文件中。

請注意,讀寫配置文件時,需要處理IOException異常。另外,配置文件的路徑可以根據(jù)實際情況進行調整。

0