使用properties文件存储临时数据(数据值过大,数据库存储不便)
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
*Java操作读写properties文件
*/
public class PropertiesFileUtil {
public static final String UTF8 = "UTF-8";
/**
* 删除文件
* @param path
* @return
*/
public static void deleteFile(String path){
File file = new File(path);
if(file.exists()) {
file.delete();
}
}
/**
* 生成文件
* @param path
* @return
*/
public static String writeFile(String path, Object obj) {
// 截取文件所属目录文件夹
String pathStr = path.substring(0, path.lastIndexOf( '/' ));
File file = new File(pathStr);
//如果文件夹不存在(防止存放文件目录不存在)
if(!file.exists()){
//创建文件夹(可创建多层)
file.mkdirs();
}
// path要精确到文件名
try(FileOutputStream fos = new FileOutputStream(path)){
// 生成实例
Properties pro = new Properties();
// 获取属性列表
Field[] fields = obj.getClass().getDeclaredFields();
// 获取属性名称和值
for (Field field:fields) {
field.setAccessible(true);
String k = field.getName();
String v = "";
// 若属性未赋值,则赋值为""
if(field.get(obj) != null){
v = field.get(obj).toString();
}
// 设置键值
pro.setProperty(k, v);
}
// 向新文件存储 使用UTF-8编码,解决中文乱码
pro.store(new OutputStreamWriter(fos, UTF8), "Init properties");
return ResultEnum.Success.getValue();
}catch (Exception e){
return ResultEnum.Failure.getValue();
}
}
/**
* 读取文件
* @param path
* @return
*/
public static String readFile(String path, Object obj) {
File file = new File(path);
if(!file.exists()) {
return ResultEnum.Nodata.getValue();
}
// java1.7新特性,自动关闭IO流
try (InputStreamReader in = new InputStreamReader(new FileInputStream(path), UTF8)){
Properties pro = new Properties();
// 使用UTF-8读取文件
pro.load(in);
//加载属性列表
Iterator it=pro.stringPropertyNames().iterator();
while(it.hasNext()){
String key= (String) it.next();
// 通过反射获取set方法,并赋值
String methodName = "set" + key.substring(0,1).toUpperCase()+key.substring(1);
Method method = obj.getClass().getDeclaredMethod(methodName,
new Class[]{
obj.getClass().getDeclaredField(key).getType()
});
method.invoke(obj, new Object[]{
pro.getProperty(key)
});
}
return ResultEnum.Success.getValue();
} catch (Exception e) {
return ResultEnum.Failure.getValue();
}
}
/**
* 修改文件(扩展使用)
* @param path
* @return
*/
public static String modifyFile(String path, Map<String, String> map){
try(InputStreamReader in = new InputStreamReader(new FileInputStream(path), UTF8)){
Properties pro = new Properties();
// 使用UTF-8读取文件
pro.load(in);
// 将修改的数据写入文件
for(Map.Entry<String, String> key : map.entrySet()){
pro.setProperty(key.getKey(), key.getValue());
}
// 查阅资料可以将输出流放到上面的try括号中,但测试时读取文件的数据是空的,不知道什么原因,所以改成这样
try(FileOutputStream fos = new FileOutputStream(path)){
pro.store(fos, "Update properties");
return ResultEnum.Success.getValue();
}catch (Exception e){
return ResultEnum.Failure.getValue();
}
}catch (Exception e){
return ResultEnum.Failure.getValue();
}
}
}