1.读取配置文件是一个很常用的操作;
读取很简单:
public static String getProperty(String key) {
String value = "";
//第一步是取得一个Properties对象
Properties props = new Properties();
//第二步是取得配置文件的输入流
InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");//在非WEB环境下用这种方式比较方便
try {
InputStream input = new FileInputStream("config.properties");//在WEB环境下用这种方式比较方便,不过当配置文件是放在非Classpath目录下的时候也需要用这种方式
//第三步讲配置文件的输入流load到Properties对象中,这样在后面就可以直接取来用了
props.load(input);
value = props.getProperty(key);
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
往配置文件写内容:
public static void setProperty(Map<String,String> data) {
//第一步也是取得一个Properties对象
Properties props = new Properties();
//第二步也是取得该配置文件的输入流
// InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");
try {
InputStream input = new FileInputStream("config.properties");
//第三步是把配置文件的输入流load到Properties对象中,
props.load(input);
//接下来就可以随便往配置文件里面添加内容了
// props.setProperty(key, value);
if (data != null) {
Iterator<Entry<String,String>> iter = data.entrySet().iterator();
while (iter.hasNext()) {
Entry<String,String> entry = iter.next();
props.setProperty(entry.getKey().toString(), entry.getValue().toString());
}
}
//在保存配置文件之前还需要取得该配置文件的输出流,<span style="color: #ff0000; font-size: medium;">切记,</span>如果该项目是需要导出的且是一个非WEB项目,则该配置文件应当放在根目录下,否则会提示找不到配置文件
OutputStream out = new FileOutputStream("config.properties");
//最后就是利用Properties对象保存配置文件的输出流到文件中;
props.store(out, null);
input.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}