我们在开发时 有很多配置|配置文件需要放在环境变量中 以便于多个项目|不同开发者 或等等原因的使用
Java为我们内置了读取环境变量的方法 这里加以简单的封装
package com.hqjl.career.util;
import com.hqjl.common.util.Common;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/**
* @author chunying
*/
public class ComfigPropertyUtil {
public static String getHQJLHome () {
// System.getenv() 是获取名为env的系统环境变量
String path = System.getenv(“env”).replace('\\', '/');
// 一般是开发自己的电脑 如果没有设置环境变量 可以自己自定义一个路径 方便开发
if (path == null) {
path = "d:/env";
}
return path;
}
public static Map<String,String> getConfigMap(){
//获取环境变量路径下 某个具体的配置文件
String combinationConfigPath = getHQJLHome() + "/config/assess/exploreOuter.properties";
Map<String, String> map = new HashMap<String, String>();
try {
//将配置文件的值通过reader流读入 一个Map
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(new File(combinationConfigPath)), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
String[] split = line.split("=");
map.put(split[0], split[1]);
}
br.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
return map;
}
}
当我们使用的时候 直接调用getConfigMap() 获取到一个map
Map的key 就是 配置等号左边的值 直接get即可