近期作指纹识别,须要用到缓存文件,数据量并不大,用redis不合适,因此用到了txt文件。redis
思路是 一、定时查询指纹,存到txt缓存文件中。数据库
二、新增或删除指纹时,查询指纹,存到txt缓存文件中。json
三、须要对比查询指纹时,从txt缓存文件中查找,若缓存文件为空,则从数据库查找。缓存
实现后,速度从9S提高到了最快0.7S。app
期间用到了 List<Map<String, Object>> 转为 json 存到txt文件中,txt 文件中的 json 内容转为 List<Map<String, Object>> 。ui
转换方式以下:spa
一、List<Map<String, Object>> 转为 json(String)code
List<Map<String, Object>> list= openDao.queryForList(map); String str = JSON.toJSONString(list); //此行转换 caChe.writeFile(finerPath,finerPath+"finerCaChe.txt",str);
writeFile 方法对象
/** * 写入TXT文件 */ public static void writeFile(String dirPath,String path,String txt) { try { judeDirExists(new File(dirPath)); File writeName = new File(path); // 相对路径,若是没有则要创建一个新的output.txt文件 writeName.createNewFile(); // 建立新文件,有同名的文件的话直接覆盖 try (FileWriter writer = new FileWriter(writeName); BufferedWriter out = new BufferedWriter(writer) ) { out.write(txt); // \r\n即为换行 out.flush(); // 把缓存区内容压入文件 } } catch (IOException e) { e.printStackTrace(); } }
二、 json 转为 List<Map<String, Object>>blog
StringBuilder line = readFile(path); //读取txt文本内容 List< Map<String,Object>> listw = toListMap(line.toString()); //此行转换
toListMap方法
public static List<Map<String, Object>> toListMap(String json){ List<Object> list =JSON.parseArray(json); List< Map<String,Object>> listw = new ArrayList<Map<String,Object>>(); for (Object object : list){ Map<String,Object> ageMap = new HashMap<String,Object>(); Map <String,Object> ret = (Map<String, Object>) object;//取出list里面的值转为map listw.add(ret); } return listw; }
readFile方法
/** * 读入TXT文件 */ public static StringBuilder readFile(String path) { String pathname = path; // 绝对路径或相对路径均可以,写入文件时演示相对路径,读取以上路径的input.txt文件 //防止文件创建或读取失败,用catch捕捉错误并打印,也能够throw; //不关闭文件会致使资源的泄露,读写文件都同理 //Java7的try-with-resources能够优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271 StringBuilder txt =new StringBuilder(""); try (FileReader reader = new FileReader(pathname); BufferedReader br = new BufferedReader(reader) // 创建一个对象,它把文件内容转成计算机能读懂的语言 ) { String line; while ((line = br.readLine()) != null) { // 一次读入一行数据 txt.append(line); } } catch (IOException e) { e.printStackTrace(); } return txt; }