1. 程式人生 > 實用技巧 >Java的IO流

Java的IO流

目錄

概念

  1. IO流:資料從外部介質(磁碟、鍵盤)輸入到記憶體為輸入流,反之為輸出流。
  2. 檔案的儲存方式:所有的檔案在硬碟或在傳輸時都是以位元組的方式進行的,字元是隻有在記憶體中才會形成。讀取位元組流後,不直接操作,而是查詢指定編碼表,就可以轉化為位元組流(如文字)。
  3. Java的位元組流和字元流
    1. 位元組流:按位元組處理,直接操作檔案本身,主要用於處理二進位制資料、視訊、圖片、檔案等。
    2. 字元流:按虛擬機器的encode來處理,要進行字符集轉化。主要用來處理文字。
  4. 父類:InputStream、OutputStream是所有位元組IO流的祖先,Reader、Writer是所有字元IO流的祖先。他們r都是抽象類,寫程式碼不能能直接new,需要使用多型方式轉化。
  5. 位元組流和字元流的區別:位元組流不使用緩衝區

操作舉例

位元組流舉例

import java.io.File;    
import java.io.FileOutputStream;    
import java.io.OutputStream;    
public class OutputStreamDemo05 {    
	public static void main(String[] args) throws Exception {  
		File f = new File("d:" + File.separator + "test.txt"); // 宣告File物件 
		//通過子類例項化父類物件 
		OutputStream out = null;  
		out = new FileOutputStream(f);  //多型例項化
		String str = "Hello World!!!";
		byte b[] = str.getBytes();
		out.write(b);
		out.close(); //因為位元組流不用緩衝區,所以即使不關閉流,也會輸出結果
		}
}

字元流舉例

import java.io.File;    
import java.io.FileWriter;    
import java.io.Writer;    
public class WriterDemo03 {    
    public static void main(String[] args) throws Exception { 
    	File f = new File("d:" + File.separator + "test.txt");
    	//通過子類例項化父類物件 
    	Writer out = null;   
    	out = new FileWriter(f); //多型例項化
    	String str = "Hello World!!!";
    	out.write(str); 
    	//out.close();//只有關閉字元流或者使用out.flush()強制清空緩衝區,才會輸出結果
    }

相互轉化

從位元組流轉化為字元流時,實際上就是byte[]轉化為String
String(byte bytes[], String charsetName)
字元流轉化為位元組流時,實際上是String轉化為byte[]
byte[] String.getBytes(String charsetName)