BufferedInputStream和BufferedOutputStream用法 解決亂碼


BufferedInputStream和BufferedOutputStream是過濾流,需要使用已存在的節點來構造,即必須先有InputStream或OutputStream,相對直接讀寫,這兩個流提供帶緩存的讀寫,提高了系統讀寫效率性能.BufferedInputStream讀取的是字節byte,因為一個漢字占兩個字節,而當中英文混合的時候,有的字符占一個字節,有的字符占兩個字節,所以如果直接讀字節,而數據比較長,沒有一次讀完的時候,很可能剛好讀到一個漢字的前一個字節,這樣,這個中文就成了亂碼,后面的數據因為沒有字節對齊,也都成了亂碼.所以我們需要用BufferedReader來讀取,它讀到的是字符,所以不會讀到半個字符的情況,不會出現亂碼.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.pocketdigi;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main {
 
	public static void main(String[] args) throws IOException {
		File f = new File("d:/a.txt");
		FileOutputStream fos = new FileOutputStream(f);
		// 構建FileOutputStream對象,文件不存在會自動新建
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		bos.write("1我是中文".getBytes());
		bos.close();
		// 關閉輸出流,寫入數據,如果下面還要寫用flush();
		// 因為是BufferOutputStream鏈接到FileOutputStream,只需關閉尾端的流
		// 所以不需要關閉FileOutputStream;
		FileInputStream fis = new FileInputStream(f);
		BufferedInputStream bis = new BufferedInputStream(fis);
		BufferedReader reader = new BufferedReader (new InputStreamReader(bis));
		//之所以用BufferedReader,而不是直接用BufferedInputStream讀取,是因為BufferedInputStream是InputStream的間接子類,
		//InputStream的read方法讀取的是一個byte,而一個中文占兩個byte,所以可能會出現讀到半個漢字的情況,就是亂碼.
		//BufferedReader繼承自Reader,該類的read方法讀取的是char,所以無論如何不會出現讀個半個漢字的.
        StringBuffer result = new StringBuffer();
        while (reader.ready()) {
            result.append((char)reader.read());
        }
		System.out.println(result.toString());
		reader.close();
 
 
	}
}

 


免責聲明!

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



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