Java 读取json文件、txt文件转为map

两种文件的读取都是通过FileInputStream和InputStreamReader,区别在于转Map的时候
json文件:

public Map parseJson(String filepath) throws IOException {
        BufferedReader reader = null;
        String laststr = "";
        FileInputStream fileInputStream = new FileInputStream(filepath);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GB2312");
        reader = new BufferedReader(inputStreamReader);
        String tempString = null;
        while ((tempString = reader.readLine()) != null) {
            laststr += tempString;
        }
        reader.close();
        Map maps = (Map) JSON.parse(laststr);
        return maps;
    }

txt文件:

 public Map parseTxt(String filepath) throws IOException {
        BufferedReader reader = null;
        String laststr = "";
        FileInputStream fileInputStream = new FileInputStream(filepath);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "GB2312");
        reader = new BufferedReader(inputStreamReader);
        String tempString = null;
        while ((tempString = reader.readLine()) != null) {
            laststr += tempString;
        }
        String news = laststr.replace(" ", "").replace("=", "");
        String[] s = news.split("\"");
        Map map = new HashMap<>();
        for (int i = 0; i < s.length; i += 2) {
            map.put(s[i], s[i + 1]);
        }
        return map;
    }

你可能感兴趣的:(Java 读取json文件、txt文件转为map)