ツールクラスからpropertiesファイルの内容を読み込む
2051 ワード
テキストアドレスhttps://www.cnblogs.com/hafiz/p/5876243.html
このクラスのstatic静的コードブロックでpropertiesファイルを読み込む内容はstaticプロパティに保存され、他のプログラムで使用できます.
説明:これにより、クラスがロードされると、指定した場所のプロファイルの内容が自動的に読み込まれ、静的プロパティに保存され、効率的で便利で、1回のロードで複数回使用できます.
このクラスのstatic静的コードブロックでpropertiesファイルを読み込む内容はstaticプロパティに保存され、他のプログラムで使用できます.
package com.hafiz.www.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/**
* Desc:properties
* Created by hafiz.zhang on 2016/9/15.
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
logger.info(" properties .......");
props = new Properties();
InputStream in = null;
try {
in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
//in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
props.load(in);
} catch (FileNotFoundException e) {
logger.error("jdbc.properties ");
} catch (IOException e) {
logger.error(" IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("jdbc.properties ");
}
}
logger.info(" properties ...........");
logger.info("properties :" + props);
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}
説明:これにより、クラスがロードされると、指定した場所のプロファイルの内容が自動的に読み込まれ、静的プロパティに保存され、効率的で便利で、1回のロードで複数回使用できます.