Java:Propertiesを使ってプロパティファイルを読み込む
Last-modified: 2013-08-24 (土) 02:14:21 (3753d)
Top / Java:Propertiesを使ってプロパティファイルを読み込む
Java:Propertiesを使ってプロパティファイルを読み込む †
Propertiesを使うサンプルです。
いつも調べているので、備忘のために、、、
ちなみに、Propertiesファイルは、
- src/resources/test.properties
にある前提です。
リソースファイルの読み込み †
ここがいつも忘れてしまうところです。
Properties conf = new Properties(); conf.load(this.getClass().getResourceAsStream("/resources/test.properties"));
リソースファイルに、Class#getResourceを使うべきか、ClassLoader?#getResourceを使うべきか。
→Class#getResourceを使って、指定するパスの先頭には必ず「/」をつける、が正解っぽいです。
ソース †
まず、プロパティファイルは以下のとおり。
■src/resources/test.properties
PROP1=test1 PROP2=test2 PROP3=test3
次に、Javaのコード
■PropertyLoader?
import java.io.IOException; import java.util.Properties; public class PropertyLoader { private Properties conf = null; public PropertyLoader() throws IOException { conf = new Properties(); conf.load(this.getClass().getResourceAsStream( "/resources/test.properties")); } public String getValue(String key){ return conf.getProperty(key); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { PropertyLoader loader = new PropertyLoader(); System.out.println(loader.getValue("PROP1")); System.out.println(loader.getValue("PROP2")); System.out.println(loader.getValue("PROP3")); } }
出力 †
こんな感じです。
test1 test2 test3