1. 程式人生 > 其它 >dat檔案資料讀取為map(java)

dat檔案資料讀取為map(java)

dat檔案的資料格式和json不一樣,python擁有庫進行檔案解析

博主找了半天,也沒找到java相關的處理包

所以自己寫了個工具類來使用

本工具類適用於博主專案

其他小夥伴需要使用的話,可能需要更改一下程式碼

其中path為讀取的dat檔案路徑

public static Map readDat(String path) {
        BufferedReader br = null;
        Map hashMap = new HashMap<String, String>();
        try {
            File file = new File(path); // java.io.File
            FileReader fr = new FileReader(file); // java.io.FileReader
            br = new BufferedReader(fr); // java.io.BufferedReader
            String line;
            boolean flag = false;
            String value = "";
            String key = "";
            while ((line = br.readLine()) != null) {
                line = line.replaceAll(" ", "");
                if (!"".equals(key) && line.contains("=")) {
                    hashMap.put(key, value);
                }
                if (line.contains("&")) {
                    continue;
                }
                if (line.contains("=")) {
                    String[] split = line.split("=");
                    key = split[0];
                    value = split[1];
                }
                if (!line.contains("=") && !line.contains("&")) {
                    if (!line.contains("/")) {
                        value += line;
                    }
                    hashMap.put(key, value);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return hashMap;
    }