properties文件读取与写入

时间:2022-01-19 13:31:32

将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();
}
}
}
} }