有两种方法:第一种直接使用,第二种封装的好点。
1
// 代表静态资源路径
private static String WEB_ROOT = System.getProperty("user.dir") + "\\" + "src\\main\\webapp";
// 还要将配置文件中的信息读取到map中
private static Map<String, String> map = new HashMap<String, String>();
// 访问之前初始化配置信息到map中
static {
// 使用javaAPI读取配置文件信息
Properties prop = new Properties();
try {
// 先加载
prop.load(new FileInputStream(WEB_ROOT + "\\conf.properties"));
// 将配置文件中的数据读取到map中、
Set set = prop.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = prop.getProperty(key);
map.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
2
这种先写一个类继承Properties
package com.yuer.mytomcat.yc;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 读取配置文件
* @author Yuer
*
*/
public class ReadConfig extends Properties{
private static final long serialVersionUID = 4896442440078075125L;
private static ReadConfig instance = new ReadConfig();
private ReadConfig() {
try(InputStream is = this.getClass().getClassLoader().getResourceAsStream("application.properties");) {
this.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static ReadConfig getInstance() {
return instance;
}
}
再使用,这种封装得好些。
ReadConfig.getInstance().getProperty("aa");
本文介绍了两种读取配置文件的方法:一种是通过直接操作文件和使用Properties类将配置信息加载到Map中;另一种是通过创建自定义类继承Properties类,实现配置文件信息的封装和便捷访问。
2786

被折叠的 条评论
为什么被折叠?



