网上关于Java读取Properties文件的总结很多,可以参考下面三位博主的博客:
Java读取Properties文件的六种方法 :http://blog.youkuaiyun.com/senton/article/details/4083127
Java读取Properties文件的思考:http://lavasoft.blog.51cto.com/62575/62174/
Java读取Properties文件方法对比:http://shmilyaw-hotmail-com.iteye.com/blog/1899242
经典方式:直接通过File Stream的经典方式来读文件,然后解析。
常用的就是采用classloader的方式:通过classloader的getResourceAsStream方法来实现加载properties文件
public class Test {
public static Properties properties = null;
public static void main(String[] args) throws IOException {
// InputStream is = Test.class.getClassLoader().getResourceAsStream("appConfig.properties");
// InputStream is = Object.class.getResourceAsStream("/appConfig.properties");
InputStream is = new BufferedInputStream (new FileInputStream("src/appConfig.properties"));
properties = new Properties();
properties.load(is);
ergodicProperties(properties);
}
private static void ergodicProperties(Properties properties) {
Iterator<Entry<Object, Object>> it = properties.entrySet().iterator();
while (it.hasNext()) {
Entry<Object, Object> entry = it.next();
System.out.println("key : " + entry.getKey()+" ,value : " + entry.getValue());
}
}
}
以上采用的方法,Properties文件所在路径必须事先设定,一般都在项目某目录下,但是如果properties文件不在项目目录下呢?
使用public static String getenv(String name)来获取指定的环境变量值。环境变量是一个取决于系统的外部指定的值。
可以设置一个环境变量:APP_HOME,该变量的值指向Properties文件所在目录,当我改变Properties文件目录,只需要修改环境变量APP_HOME即可。
public class Test {
private static String systemFilePath = null;
private static Properties properties = null;
public static void main(String[] args) {
if(getSystemFilePath() == null){
throw new RuntimeException("APP_HOME 系统环境变量未设置!");
}
properties = new Properties();
try {
properties.load(new FileInputStream(getSystemFilePath()+"/system.properties"));
} catch (IOException e) {
e.printStackTrace();
}
ergodicProperties(properties);
}
/**
* 遍历Properties内容
*
* @param properties
*/
private static void ergodicProperties(Properties properties) {
Iterator<Entry<Object, Object>> it = properties.entrySet().iterator();
while (it.hasNext()) {
Entry<Object, Object> entry = it.next();
//实际项目中可以采用日志输出
System.out.println(entry.getKey()+" : " + entry.getValue());
}
}
/**
* 获取系统变量
* @return
*/
private static String getSystemFilePath(){
if(!isEmpty(systemFilePath)){
return systemFilePath;
}
systemFilePath = System.getenv("APP_HOME");
System.out.println("系统文件路径:APP_HOME[" + systemFilePath + "]");
return systemFilePath;
}
/**
* 判断字符是为空
*
* @param str
* @return
*/
private static boolean isEmpty(Object str) {
if(str == null) return true;
String checkStr = str.toString();
return checkStr == null ? true : (checkStr.trim().length()==0 || "null".equalsIgnoreCase(checkStr.trim()) ? true : false);
}
}