「java」properties ファイルからの値の取得方法まとめ

1.db.properties
url=xxx
user=xxx;
password=xxx;

2.プロパティファイルの読み込み
ServletContext context = this.getServletContext();

//方法1
URL url = context.getResource(“WEB-INF/classes/db.properties");
InputStream is = url.openStream();

//方法2
String path =context.getRealPath(“WEB-INF/classes/db.properties");
File file = new File(path);
InputStream is = new FileInputStream(file);

//方法3
InputStream is = context.getResourceAsStream(“WEB-INF/classes/db.properties “);

3.プロパティファイルの値を取得
Properties prop = new Properties();
prop.load(is);

Set set = prop.stringPropertyNames();
//setの要素を遍歴
Iterator it = set.iterator();
while(it.hasNext()){
String key = it.next();
String value = prop.getProperty(key);
System.out.println(key+"—–“+value);
}

Java

Posted by arkgame