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;
public class PropertiesUtil {
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);
}
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;
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();
}
}
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;
}
}