1. 程式人生 > 實用技巧 >Java—字元流

Java—字元流

一、字元流

字元流概述:

在操作過程中位元組流可以操作所有資料,操作的檔案中有中文字元,並且需要對

中文字元做出處理

二、字元編碼表

文字——>(數字):編碼。"abc".getBytes() byte[]

數字——>(文字):解碼。byte[] b = {97, 98, 99} new String(b)

三、字元輸入流Reader

FileReader類

此類的構造方法假定預設字元編碼和預設位元組緩衝區大小都是適當的;用來操作檔案的字元輸入流(簡便的流)

使用位元組流讀寫中文字元
public class CharStreamDemo {
	
	public static void main(String[] args) throws IOException {
		// 給檔案中寫中文
		writeCNText();
		
		// 讀取檔案中的中文,讀取的都是數字,跟字元編碼表有關
		readCNText();
	}
	
	public static void readCNText() throws IOException {
		InputStream is = new FileInputStream("e:/file.txt");
		int ch = 0;
		while((ch = is.read()) != -1){
			System.out.println(ch);
		}
		
		is.close();
	}

	public static void writeCNText() throws IOException {
		OutputStream os = new FileOutputStream("e:/file.txt");
		os.write("Java歡迎您~~~".getBytes());
		os.close();
	}
	
}
使用字元輸出流讀取字元

用來操作檔案的字元輸出流(簡便的流)

public class CharStreamDemo {
	
	public static void main(String[] args) throws IOException {
		// 給檔案中寫中文
		writeCNText();
		
		// 讀取檔案中的中文
		readCNText();
		
	}
	
	public static void readCNText() throws IOException {
		Reader reader = new FileReader("e:/file.txt");
		int ch = 0;
		while((ch = reader.read()) != -1){
			// 輸入的字元對應的編碼
			System.out.print(ch + " = ");
			
			// 輸入字元本身
			System.out.println((char) ch);
		}
		
		reader.close();
	}

	public static void writeCNText() throws IOException {
		OutputStream os = new FileOutputStream("e:/file.txt");
		os.write("Java歡迎您~~~".getBytes());
		os.close();
	}
	
}

四、字元輸入流Writer

FileWriter類

寫入字元到檔案中,先進行流的重新整理,再進行流的關閉

flush() & close() 的區別

flush():將流中的緩衝區緩衝的資料重新整理到目的地中,重新整理後,流還可以繼續使用

close():關閉資源,但在關閉前會將緩衝區中的資料先重新整理到目的地,否則丟失資料,然後再關閉流。流不可以使用。如果寫入資料多,一定要一邊寫一邊重新整理,最後一次可以不重新整理,由close完成重新整理並關閉。

public class FileWriterDemo {
	public static void main(String[] args) throws IOException {
		Writer writer = new FileWriter("e:/text.txt");
		writer.write("你好,謝謝,再見");
		/*
		 * flush() & close()
		 * 區別:
		 * flush():將流中的緩衝區緩衝的資料重新整理到目的地中,重新整理後,
		 * 			流還可以繼續使用
		 * close():關閉資源,但在關閉前會將緩衝區中的資料先重新整理到目的地,
		 * 		          否則丟失資料,然後再關閉流。流不可以使用。
		 * 			如果寫入資料多,一定要一邊寫一邊重新整理,最後一次可以不重新整理,
		 * 			由close完成重新整理並關閉。
		 */
		writer.flush();
		writer.close();
	}
}