properties文件读取与写入
将peoperties文件的读取和写入封装成了一个工具类:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class PropertyUtil {
/**
* 读取properties文件
* @param fileName
* @return
*/
public static Map<String, String> getProperties(String fileName) {
Map<String, String> propertyMap = new HashMap<String, String>();
Properties properties = new Properties();
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(fileName));
properties.load(in);
Iterator<String> itr = properties.stringPropertyNames().iterator();
while (itr.hasNext()) {
String key = itr.next();
String value = properties.getProperty(key);
propertyMap.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return propertyMap;
}
/**
* 将properties保存成文件
* @param properties
* @param fileName
* @param comments
*/
public static void saveProperties(Map<String, String> properties,
String fileName, String comments) {
Properties property = new Properties();
FileOutputStream out = null;
try {
out = new FileOutputStream(fileName);
Set<Map.Entry<String, String>> entrySet = properties.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
String key = entry.getKey();
String value = entry.getValue();
property.setProperty(key, value);
}
property.store(out, comments);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
![](https://files.cnblogs.com/files/acode/sub.bmp)
作者: Acode
出处: http://www.cnblogs.com/acode/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可留言咨询.