解決IO流讀取TXT亂碼

public void readerTxt() {
    String filePath = "D:/在職客戶經理信息自動維護.txt";
    BufferedReader bufferedReader = null;
    try {
        //getCode(filePath)獲取文件的編碼格式
        bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)),getCode(filePath)));
        String strLine = "";
        while ((strLine = bufferedReader.readLine()) != null) {
            System.out.println(strLine);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

// 獲取編碼格式 gb2312,UTF-16,UTF-8,Unicode,UTF-8
public static String getCode(String path) throws Exception {
    InputStream inputStream = new FileInputStream(path);
    byte[] head = new byte[3];
    inputStream.read(head);
    String code = "gb2312"; // 或GBK
    if (head[0] == -1 && head[1] == -2) {
        code = "UTF-16";
    } else if (head[0] == -2 && head[1] == -1) {
        code = "Unicode";
    } else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
        code = "UTF-8";
    }
    inputStream.close();
    return code;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章