IO流讀寫文件中文亂碼的解決


  • 問題描述

    在使用 Java 讀寫文件的過程中,當涉及到中文字符,會出現亂碼的問題,讀取內容與預期結果不符。

  • 問題分析

    所有的文件都是有編碼格式的,其中 txt 和 Java 文件一般有三種編碼格式:ISO8859-1、GSK 和 UTF-8.

    其中 ISO8859-1 是西歐編碼,不適用中文漢字;GSK 和 UTF-8 適用於中文。Windows 10下默認的編碼格式是 UTF-8.

    基於此,使用不同的編碼格式讀寫文件,就會產生亂碼。例如,eclipse 下默認的編碼格式為 GBK,直接使用字符流讀取會產生如下亂碼。

    • 代碼部分
        /**
	 * 緩沖字符流讀文件
	 * @param inPath
	 * @return
	 * @throws Exception
	 */
	public static String testBufferedReader(String inPath) throws Exception {
		BufferedReader bi = new BufferedReader(new FileReader(inPath));
		StringBuffer sbr = new StringBuffer();
		String s = null;

		while((s = bi.readLine()) != null) {
			sbr.append(s);
		}
		s = sbr.toString();
		bi.close();
		
		return s;
	}
- 測試用例

- 測試結果

  • 解決方案

    使用轉換流 InputStreamReader 和 OutputStreamWriter 按指定字符集解碼文件,可解決這一問題。

    • 代碼部分
        /**
	 * 緩沖字符流讀文件
	 * @param inPath
	 * @return
	 * @throws Exception
	 */
	public static String testBufferedReader(String inPath) throws Exception {
		BufferedReader bi = new BufferedReader(new InputStreamReader(new FileInputStream(inPath), "UTF-8"));
		StringBuffer sbr = new StringBuffer();
		String s = null;

		while((s = bi.readLine()) != null) {
			sbr.append(s);
		}
		s = sbr.toString();
		bi.close();
		
		return s;
	}
- 測試用例

- 測試結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM