一.字節流
單個字節讀取
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("D:\\bf\\Desktop\\test.txt");//字節流
int data = in.read();
while(data != -1){
System.out.print((char)data);
data = in.read();
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
結果分析:可以看出結果出現了亂碼,這是因爲UTF-8文件下一個中文是兩個字節,三個字節或四個字節。。。,單字節讀取出現了亂碼。
多個字節讀取
try {
byte [] b = new byte[1024];
//System.out.print("𠀁".getBytes("UTF-8").length);//輸出4,即4個字節
FileInputStream in = new FileInputStream("D:\\bf\\Desktop\\test.txt");//字節流
//BufferedInputStream bu = new BufferedInputStream(in);//BufferedInputStream是一種封裝別的流以提高效率的流,它的初始化需要一個的InputStream流對象
int n = in.read(b);
//int n = bu.read(b);
while(n != -1){
System.out.print(new String(b, 0, n));//確保輸出的是每次讀取的,避免上次讀取的數組
對結果的影響
n = in.read(b);
//n = bu.read(b);
}
in.close();
//bu.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
結果分析:可以看出短文本能夠正在顯示,這是因爲一次性讀取完全,沒有讀取一箇中文部分字節的情況,保持了文本的完整性。
注意:UTF-8下中文的字節長度有可能是2、3或4…若讀取一個數組長度字節,很難確定長度範圍,所以讀取文本應儘量避免使用字節流,應使用字符流。