项目中将一些变量配置到properties资源文件中,可以起到方便修改的作用,这里可以用PropertiesUtil工具类进行读取文件内容。
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class PropertiesUtil {
public static Map<String, String> loadProperties(String path) {
Map<String, String> map = new HashMap<String, String>();
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(path);//资源文件与classpath的相对路径
// InputStream in = Test2.class.getResourceAsStream(path);//资源文件与PropertiesUtil的相对路径
if(null==in){
return map;
}
try {
Properties pros = new Properties();
pros.load(in);
Enumeration en = pros.propertyNames();// 得到资源文件中的所有key值
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
map.put(key, pros.getProperty(key));
}
return map;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
System.err.println("关闭流失败");
}
}
return map;
}
}