Javaプロパティファイルの例

Javaプロパティファイルの例

通常、Javaプロパティファイルはプロジェクト設定データまたは設定を保存するために使用されます。 このチュートリアルでは、.propertiesファイルの読み取りと書き込みの方法を示します。

    Properties prop = new Properties();

    // set key and value
    prop.setProperty("db.url", "localhost");
    prop.setProperty("db.user", "example");
    prop.setProperty("db.password", "password");

    // save a properties file
    prop.store(outputStream, "");

    // load a properties file
    prop.load(inputStream)

    // get value by key
    prop.getProperty("db.url");
    prop.getProperty("db.user");
    prop.getProperty("db.password");

    // get all keys
    prop.keySet();

    // print everything
    prop.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));

テスト用のシンプルなMavenプロジェクト構造。

project directory

1. プロパティファイルへの書き込み

プロパティのキーと値を設定し、どこかに保存します。

App1.java

package com.example;

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

public class App1 {

    public static void main(String[] args) {

        try (OutputStream output = new FileOutputStream("path/to/config.properties")) {

            Properties prop = new Properties();

            // set the properties value
            prop.setProperty("db.url", "localhost");
            prop.setProperty("db.user", "example");
            prop.setProperty("db.password", "password");

            // save properties to project root folder
            prop.store(output, null);

            System.out.println(prop);

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

    }
}

出力

{db.user=example, db.password=password, db.url=localhost}

path/to/config.propertiesが作成されます。

path/to/config.properties

#Thu Apr 11 17:37:58 SRET 2019
db.user=example
db.password=password
db.url=localhost

2. プロパティファイルを読み込む

ファイルシステムからプロパティファイルを読み込み、プロパティ値を取得します。

App2.java

package com.example;

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

public class App2 {

    public static void main(String[] args) {

        try (InputStream input = new FileInputStream("path/to/config.properties")) {

            Properties prop = new Properties();

            // load a properties file
            prop.load(input);

            // get the property value and print it out
            System.out.println(prop.getProperty("db.url"));
            System.out.println(prop.getProperty("db.user"));
            System.out.println(prop.getProperty("db.password"));

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

    }

}

出力

localhost
example
password

3. クラスパスからプロパティファイルを読み込む

プロジェクトのクラスパスからプロパティファイルconfig.propertiesをロードし、プロパティ値を取得しました。

src/main/resources/config.properties

db.url=localhost
db.user=example
db.password=password

App3.java

package com.example;

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

public class App3 {

    public static void main(String[] args) {

        try (InputStream input = App3.class.getClassLoader().getResourceAsStream("config.properties")) {

            Properties prop = new Properties();

            if (input == null) {
                System.out.println("Sorry, unable to find config.properties");
                return;
            }

            //load a properties file from class path, inside static method
            prop.load(input);

            //get the property value and print it out
            System.out.println(prop.getProperty("db.url"));
            System.out.println(prop.getProperty("db.user"));
            System.out.println(prop.getProperty("db.password"));

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

    }

}

出力

localhost
example
password

4. プロパティファイルからすべてを印刷します

プロジェクトのクラスパスからプロパティファイルconfig.propertiesをロードし、キーと値を出力します。

App4.java

package com.example;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

public class App4 {

    public static void main(String[] args) {
        App4 app = new App4();
        app.printAll("config.properties");
    }

    private void printAll(String filename) {

        try (InputStream input = getClass().getClassLoader().getResourceAsStream(filename)) {

            Properties prop = new Properties();

            if (input == null) {
                System.out.println("Sorry, unable to find " + filename);
                return;
            }

            prop.load(input);

            // Java 8 , print key and values
            prop.forEach((key, value) -> System.out.println("Key : " + key + ", Value : " + value));

            // Get all keys
            prop.keySet().forEach(x -> System.out.println(x));

            Set objects = prop.keySet();

            /*Enumeration e = prop.propertyNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String value = prop.getProperty(key);
                System.out.println("Key : " + key + ", Value : " + value);
            }*/

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

    }

}


出力

Key : db.user, Value : example
Key : db.password, Value : password
Key : db.url, Value : localhost
db.user
db.password
db.url

ソースコードをダウンロード

ダウンロード–java-properties-file.zip(6KB)