JavaでProperties設定ファイルを読み書きする方法は何ですか?

Javaでは、Properties設定ファイルの読み書きにはjava.util.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例外を処理する必要があります。また、設定ファイルのパスは実際の状況に応じて調整することができます。

bannerAds