通常开发java项目的时候,会用到自定义的properties文件,这里描述一种可以在项目中方便大家直接读取properties文件的方法。
Properties文件内容如下:
#XML file location
xmlRootPath=/mnt/share/Reserved/check
#Photo location
photoRootPath=/mnt/share/Reserved/check
Stage=DEV
单例类代码如下:
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
public class ID5PrjConfig {
private static Logger log = Logger.getLogger(ID5PrjConfig.class);
static class CLLConfigHolder {
static ID5PrjConfig instance = new ID5PrjConfig();
}
public static ID5PrjConfig getInstance() {
return CLLConfigHolder.instance;
}
private ID5PrjConfig() {
props = new Properties();
InputStream in = null;
try {
in = ID5PrjConfig.class.getClassLoader().getResourceAsStream("ID5PrjConfig.properties");
props.load(in);
} catch (Exception e) {
log.error(e.getMessage());
//e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
}
}
}
}
public String getValue(String key) {
return props.getProperty(key, "");
}
private Properties props =null;
}
<script src="https://code.csdn.net/snippets/752284.js"></script>
在另外一个类中调用只需要一行代码:
String str = ID5PrjConfig.getInstance().getValue("Stage")
这里拿到的str就是“DEV”。