LoginSignup
43
49

More than 5 years have passed since last update.

Java Propertyファイル読み込み

Last updated at Posted at 2017-11-11

今回はJavaのPropertyファイルの読みこみ方法について紹介します。

Propertyファイルとは

Propertyファイルとは、キーと値が対になったデータを保存しているファイルです。Windowsのiniファイルとかと同じです。
プログラムの設定値などを保存しておくファイルとして使用します。
Propertyファイルに記述しておくと、コンパイルなしでプログラムの動作を変更できるので後で変わる可能性のある値とか設定すると良いと思います。
例えば、ユーザID、パスワードとか。

フォーマット

記述フォーマットは、キーと値を「=(イコール)」でつないで記述します。
具体的には以下のような感じです。

キー=値

また、行頭に記述された「#(シャープ)」より後ろはコメントを表します。

#この行はコメントです。
キー1=値
キー2=値#
キー3#=値

この場合、「キー2」に対応する値は、「値#」になります。また、「キー3#」に対応する値は「値」になります。

Propertyファイルを読み込む

Propertyファイルを読み込むためには、java.util.Propertiesを使用します。
実際のプログラムを見るほうが早いと思うので具体例を記述してみます。

public class PropertyUtil {

    private static final String INIT_FILE_PATH = "resourse/common.properties";
    private static final Properties properties;

    private PropertyUtil() throws Exception {
    }

    static {
        properties = new Properties();
        try {
            properties.load(Files.newBufferedReader(Paths.get(INIT_FILE_PATH), StandardCharsets.UTF_8));
        } catch (IOException e) {
            // ファイル読み込みに失敗
            System.out.println(String.format("ファイルの読み込みに失敗しました。ファイル名:%s", INIT_FILE_PATH));
        }
    }

    /**
     * プロパティ値を取得する
     *
     * @param key キー
     * @return 値
     */
    public static String getProperty(final String key) {
        return getProperty(key, "");
    }

    /**
     * プロパティ値を取得する
     *
     * @param key キー
     * @param defaultValue デフォルト値
     * @return キーが存在しない場合、デフォルト値
     *          存在する場合、値
     */
    public static String getProperty(final String key, final String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }

Propertyファイルを読み込むのに、Propertiesのload関数を使用します。
loadは、Readerを引数に受け取りますので、Propertyファイルを読み込んだReaderを使用してください。
読み込んだPropertyファイルの値は、キーを指定してgetProperty関数で取得できます。
では、使用例を記述してみます。

common.properties
test=テスト値

    public static void main(String[] args) {
        System.out.println(PropertyUtil.getProperty("test")); // ⇒ テスト値
    }

このようにキーを指定するとそれに対応する値を取得できます。

以上です。

43
49
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
49