Java语言读取配置文件config.properties的方法讲解
时间:2021-04-14 09:05:58|栏目:Android代码|点击: 次
应用场景
有些时候项目中会用到很多路径,并且很可能多个路径在同一个根目录下,那为了方便配置的修改,达到只修改根目录即可达到一改全改的效果,此时就会想到要是有变量就好了;
另外有时候路径中的文件名是不确定的,要靠业务程序运行时去判断文件名应该如何设置,而又希望此文件下的目录名是确定的,那此时用变量也是比较好的解决方式。
一、配置文件config.properties是放在src根目录下的:例如我的是 /PropertiesTest/src/com/xuliugen/project/type.properties
配置文件中的内容如下:
left=com.sunny.project.LeftHair right=com.sunny.project.RightHair in=com.sunny.project.InHair
读取配置文件中的代码如下:
public class PropertiesReader {
public static void main(String[] args) {
new PropertiesReader().getProperties();
}
public Map<String, String> getProperties() {
Properties props = new Properties();
Map<String, String> map = new HashMap<String, String>();
try {
InputStream in = getClass().getResourceAsStream("type.properties");
props.load(in);
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String property = props.getProperty(key);
map.put(key, property);
System.out.println(key + " " + property);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
运行结果如下:

总结
栏 目:Android代码
下一篇:Android自定义控件实现圆形进度CircleProgressBar
本文标题:Java语言读取配置文件config.properties的方法讲解
本文地址:http://www.codeinn.net/misctech/101217.html






