您好,登錄后才能下訂單哦!
java讀取txt文件,如果編碼格式不匹配,就會(huì)出現(xiàn)亂碼現(xiàn)象。所以讀取txt文件的時(shí)候需要設(shè)置讀取編碼。txt文檔編碼格式都是寫(xiě)在文件頭的,在程序中需要先解析文件的編碼格式,獲得編碼格式后,在按此格式讀取文件就不會(huì)產(chǎn)生亂碼了。
java編碼與txt編碼對(duì)應(yīng):
示例:
package com.lfl.attachment; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; public class TextMain { public static void main(String[] args) throws Exception { String filePath = "D:/article.txt"; // String filePath = "D:/article333.txt"; // String filePath = "D:/article111.txt"; String content = readTxt(filePath); System.out.println(content); } /** * 解析普通文本文件 流式文件 如txt * @param path * @return */ @SuppressWarnings("unused") public static String readTxt(String path){ StringBuilder content = new StringBuilder(""); try { String code = resolveCode(path); File file = new File(path); InputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is, code); BufferedReader br = new BufferedReader(isr); // char[] buf = new char[1024]; // int i = br.read(buf); // String s= new String(buf); // System.out.println(s); String str = ""; while (null != (str = br.readLine())) { content.append(str); } br.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("讀取文件:" + path + "失敗!"); } return content.toString(); } public static String resolveCode(String path) throws Exception { // String filePath = "D:/article.txt"; //[-76, -85, -71] ANSI // String filePath = "D:/article111.txt"; //[-2, -1, 79] unicode big endian // String filePath = "D:/article222.txt"; //[-1, -2, 32] unicode // String filePath = "D:/article333.txt"; //[-17, -69, -65] UTF-8 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(); System.out.println(code); return code; } }
注意:在resolveTxt方法中不能通過(guò)readTxt方法傳InputStream流 ,這樣會(huì)使兩個(gè)方法持有同一個(gè)流引用,而在resolveTxt方法中已讀過(guò)流中的三個(gè)字節(jié),流中的pos此時(shí)已經(jīng)是3了,而不是流的起始位置,再在readTxt中讀取時(shí)就會(huì)出現(xiàn)IOException:Read Error。
以上就是java讀取txt文件亂碼解決方法的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注億速云其它相關(guān)文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。