代码:
package com.sux.demo.utils; import com.alibaba.fastjson.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; /** * 存储工具类 */ public class StoreUtil { private static final String fileDir = "/home/server/import/wifi/log/"; private static final String fileName = "store-kafka-delay-check.log"; private static Object lock = new Object(); public static void write(String key, Object value) throws IOException { Map<String, Object> map = read(); if (map.containsKey(key)) { map.remove(key); } map.put(key, value); String strJson = JSONObject.toJSONString(map); synchronized (lock) { mkdirs(); FileOutputStream fos = new FileOutputStream(fileDir + fileName); byte[] bytes = strJson.getBytes(Charset.forName("utf-8")); fos.write(bytes); fos.close(); } } public static Object read(String key) throws IOException { Map<String, Object> map = read(); if (map.containsKey(key)) { return map.get(key); } return null; } private static Map<String, Object> read() throws IOException { synchronized (lock) { mkdirs(); File file = new File(fileDir + fileName); if (file.exists() && file.isFile()) { FileInputStream fis = new FileInputStream(fileDir + fileName); byte[] bytes = new byte[fis.available()]; fis.read(bytes, 0, bytes.length); fis.close(); String strJson = new String(bytes, Charset.forName("utf-8")); return JSONObject.parseObject(strJson); } else { return new HashMap<>(); } } } private static void mkdirs() { File file = new File(fileDir); if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } } }
自己写的一个服务程序需要这个功能,为什么我会需要一个这么low的工具类呢?