Java - 自定义Key-Value读写工具

发布于:2025-02-10 ⋅ 阅读:(64) ⋅ 点赞:(0)

Java - 自定义Key-Value读写工具

本地k-v缓存工具类
1. 注释行以 # 开头;
2. = 左右不要留空格;
3. 案例仅String类型,其他类型转换即可;
使用:
//读取
String syncTime = PropertiesUtil.getInstance().getSyncTime();
CommonUtil.printLog("syncTime: " + syncTime);
//写入
PropertiesUtil.getInstance().setSyncTime(CommonUtil.getCurTime(Config.STR.FORMAT_ALL));

在这里插入图片描述

在这里插入图片描述

PropertiesUtil.java
package util;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 本地k-v缓存工具类
 * ps:
 * 1. 注释行以 # 开头;
 * 2. = 左右不要留空格;
 */
public class PropertiesUtil {
    //自定义key
    public static final String KEY_SYNCTIME = "syncTime";

    private static PropertiesUtil instance = null;
    private String CACHE_PATH;//文件路径

    // 单例模式
    public static PropertiesUtil getInstance() {
        if (instance == null) {
            synchronized (PropertiesUtil.class) {
                if (instance == null) {
                    instance = new PropertiesUtil();
                }
            }
        }
        return instance;
    }

    public PropertiesUtil() {
        //项目内|项目外的文件路径
        this.CACHE_PATH = Constants.BOOL.IS_RELEASE ? "pro/cache.pro" : "./MFrame/res/pro/cache.pro";
    }

    public String getSyncTime() {
        return getValue(KEY_SYNCTIME, "");
    }

    public void setSyncTime(String value) {
        updateValue(KEY_SYNCTIME, value);
    }

    /**
     * 新增|更新 K-V 值
     * 尾部追加,已存在的则其后行往上覆盖
     *
     * @param key   key
     * @param value value
     */
    private void updateValue(String key, String value) {
        File file = new File(CACHE_PATH);
        if (!file.exists()) {
            CommonUtil.printLog("文件不存在!");
            return;
        }

        String cont = key + "=" + value;
        RandomAccessFile accessFile;
        try {
            accessFile = new RandomAccessFile(file, "rw");
            StringBuilder builder = new StringBuilder();
            int seekPosition = 0;//目标位置
            int offset = -1;//目标行前行数-1
            String line;
            boolean hasFind = false;
            while (null != (line = accessFile.readLine())) {
                if (hasFind) {
                    //目标行后面数据
                    builder.append("\n").append(line);
                    continue;
                }

                if (!line.startsWith("#")) {
                    //非注释
                    if (line.contains(key)) {
                        hasFind = true;
                        continue;
                    }
                }
                offset++;

                seekPosition += line.length();
            }

            //尾部添加
            builder.append("\n").append(cont);
            //全新
            if (hasFind) {
                //更新
                CommonUtil.printLog("更新:" + key);
                accessFile.seek(seekPosition + offset);
                accessFile.writeBytes(builder.toString());
                accessFile.setLength(builder.toString().length() + seekPosition + offset);
            } else {
                //全新
                CommonUtil.printLog("新增:" + key);
                accessFile.writeBytes(builder.toString());
            }
            accessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 按键值查找
     *
     * @param key key
     * @param def 默认值
     * @return str
     */
    private String getValue(String key, String def) {
        File file = new File(CACHE_PATH);
        if (!file.exists()) {
            CommonUtil.printLog("文件不存在!");
            return def;
        }
        String value = def;
        RandomAccessFile accessFile;
        try {
            accessFile = new RandomAccessFile(file, "r");

            // 按行分类解析
            String line;
            while ((line = accessFile.readLine()) != null) {
                if (line.startsWith("#")) {
                    continue;//注释
                }
                if (line.contains("=")) {
                    String[] arr = line.split("=");
                    if (arr[0].equals(key)) {
                        value = arr[1].trim();
                    }
                    break;
                }
            }
            accessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return value;
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到