1. 程式人生 > >java輸入輸出14:IO流(位元組流讀寫中文)

java輸入輸出14:IO流(位元組流讀寫中文)

位元組流讀取中文的問題

位元組流在讀中文的時候有可能會讀到半個中文,造成亂碼。

位元組流寫出中文的問題

位元組流直接操作位元組,所以寫出中文必須將字串轉換成位元組陣列。寫出回車換行write("\r\n".getBytes())。

檔案11.txt:

在這裡插入圖片描述

案例
package filePackage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Demo12_Chinese {
	
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream("11.txt");
		FileOutputStream fos = new FileOutputStream("copy.txt");
		byte[] arr = new byte[3];
		int len;
		while ((len = fis.read(arr)) != -1) {
			System.out.println(new String(arr,0,len));
		}
		
		fos.write("好好學習,天天向上".getBytes());
		fos.write("\r\n".getBytes());
		fis.close();
		fos.close();
	}
}

執行結果:
在這裡插入圖片描述
檔案copy.txt:
在這裡插入圖片描述