Javaでプロパティファイルを読み込む

2020年3月13日

クラスパス上のプロパティファイルの内容をPropertiesクラスのオブジェクトに読込み保持します。
シングルパターンを実装しており、プロパティファイルの読込は初回のインスタンス取得時のみ行います。

ClassクラスのgetResourceAsStreamメソッドはクラスパス上のプロパティファイルを読込むために使用します。

resourceフォルダを作成し、eclipseからソースフォルダに追加したとすると、resourceフォルダ内のファイルはgetResourceAsStream(“/ファイル名")でアクセスできます。resourceフォルダ内にパッケージ1.パッケージ2.プロパティファイルと配置したとすると、getResourceAsStream(“/パッケージ1/パッケージ2/ファイル名")となります。


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

public final class SystemPropertyUtils {

    private static SystemPropertyUtils instance;
    Properties systemConf;

    /**
    * プライベートコンストラクタ
    * @throws IOException
    */
    private SystemPropertyUtils() throws IOException {
        init();
    }

    /**
     * System.propertiesファイルをロード
     * @throws IOException
     * @throws IOException
     */
     private void init() throws IOException, IOException {
         systemConf = new Properties();
         systemConf.load(this.getClass().getResourceAsStream("/System.properties"));
     }

    /**
     * イングルトンのインスタンスを返す。
     * @return SystemPropertyUtilsのイングルトンインスタンス。
     * @throws IOException
     */
    public static synchronized SystemPropertyUtils getInstance() throws IOException {
        if (instance != null) {
            return instance;
        } else {
            instance = new SystemPropertyUtils();
            return instance;
        }
    }

     /**
      * 引数で指定されたキーに対するプロパティファイルの値を返す。
      * @param key プロパティファイル中のキー。
      * @return キーに対応する値。
      */
      public String getValue(String key) {
          return instance.systemConf.getProperty(key);
      }
}

Java

Posted by fanfanta