com.gitee.aachen0.util.Property Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of autil-util Show documentation
Show all versions of autil-util Show documentation
java programing enhanced util
package com.gitee.aachen0.util;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* 属性文件properties和Map之间的相互转换
*/
public class Property {
/**
* 从一个properties文件中获取一个Map集合
*
* @param propPath 需要读取的properties文件
* @return 属性集合
* @throws IOException IO异常
*/
public static Map getMap(String propPath) throws IOException {
Map map = new HashMap<>();
Properties properties = new Properties();
String extension = Strings.getExtension(propPath);
if ("properties".equals(extension)) {
properties.load(new FileReader(propPath));
} else if ("xml".equals(extension)) {
properties.loadFromXML(new FileInputStream(propPath));
} else throw new IllegalArgumentException("文件类型不正确!");
Set keys = properties.stringPropertyNames();
for (String key : keys) {
map.put(key, properties.getProperty(key));
}
return map;
}
/**
* 将一个Map的数据持久化到properties文件内,Map内容请使用UTF-8编码方式
*
* @param map 要存放的Map
* @param propPath properties文件路径
* @param comments 注释
* @return 存放结果
* @throws IOException IO异常
*/
public static boolean mapToProp(Map map, String propPath, String comments) throws IOException {
boolean result = false;
Properties properties = new Properties();
Set keys = map.keySet();
if (keys.size() <= 0) return false;
File prop = new File(propPath);
if (!prop.exists()) {
result = prop.createNewFile();
}
for (String key : keys) {
properties.setProperty(key, map.get(key));
}
String extension = Strings.getExtension(propPath);
if ("properties".equals(extension)) {
properties.store(new FileWriter(prop), comments);
} else if ("xml".equals(extension)) {
properties.storeToXML(new FileOutputStream(propPath), comments);
}
return result;
}
/**
* 将一个Map的数据添加到一个properties文件内,Map内容请使用UTF-8编码方式
*
* @param map 要添加的Map
* @param propPath properties文件路径
* @param comments 注释
* @return 添加结果
* @throws IOException IO异常
*/
public static boolean mapUpdateToProp(Map map, String propPath, String comments) throws IOException {
if (map == null || map.size() <= 0) return false;
Map originMap = getMap(propPath);
originMap.putAll(map);
return mapToProp(originMap, propPath, comments);
}
}