Java操作properties文件存储数据

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

    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

k_trouble

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值