List<Map<String, Object>> 与 json 互转

近期做指纹识别,需要用到缓存文件,数据量并不大,用redis不合适,所以用到了txt文件。

思路是 1、定时查询指纹,存到txt缓存文件中。

       2、新增或删除指纹时,查询指纹,存到txt缓存文件中。

    3、需要对比查询指纹时,从txt缓存文件中查找,若缓存文件为空,则从数据库查找。

实现后,速度从9S提升到了最快0.7S。

期间用到了 List<Map<String, Object>> 转为 json 存到txt文件中,txt 文件中的 json 内容转为 List<Map<String, Object>> 。

转换方式如下:

1、List<Map<String, Object>> 转为 json(String)

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

2、 json 转为 List<Map<String, Object>>

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;
    }

猜你喜欢

转载自www.cnblogs.com/remember-forget/p/10454738.html