IO 輸入輸出流和字元流

2022-09-09 10:57:16 字數 3043 閱讀 1249

•輸入輸出(i/o)

把電腦硬碟上的資料讀到程式中,稱為輸入,即input,進行資料的read操作

從程式往外部裝置寫資料,稱為輸出,即output,進行資料的write操作

•inputstream和outputstream的子類都是位元組流

-可以讀寫二進位制檔案,主要處理音訊、、歌曲、位元組流,處理單元為1個位元組。

•reader和writer的子類都是字元流

​ 主要處理字元或字串,字元流處理單元為1個字元。

​ 位元組流將讀取到的位元組資料,去指定的編碼表中獲取對應文字。

public static void main(string args)  catch (ioexception e) 

}

輸入輸出成對出現

public static void main(string args) 

} catch (filenotfoundexception e) catch (ioexception e) finally

if (out != null)

} catch (ioexception e) }}

有效**

public static void main(string args) throws ioexception 

in.close();

out.close();

}

讀寫效率的提公升

package com.ff.j**aio.day2;

import j**a.io.fileinputstream;

import j**a.io.fileoutputstream;

import j**a.io.ioexception;

public class streamdemo3

in.read(b);

in.close();

out.close();}}

public static void main(string args) throws ioexception */

int length = 0;

byte b = new byte[1024];

while ((length = bin.read(b)) != -1)

bout.flush();//重新整理緩衝區

bout.close();

bin.close();

}

字元流,以字元為單位讀寫資料

reader

轉換流 inpustreamreader

filereader

bufferedreader

writer

轉換流 outstreamwriter

filewriter

bufferedwriter

reader 的基本方法 讀取乙個字元並以整數的形式返回, 如果返回-1已到輸入流的末尾。

writer 的基本方法向輸出流中寫入乙個字元資料,該位元組資料為引數b的16位

public static void main(string args) throws ioexception */

//讀取為字元型別陣列

char c = new char[5];

int length;

while((length= reader.read(c))!=-1)

writer.close();

reader.close();

}

filewriter方法中有字元拼接,寫入時不會覆蓋原來的內容,會在後面繼續拼接

bufferedwriter中readline();方法,實現了每次可以讀取檔案中一行的功能

public static void main(string args) throws ioexception 

bwriter.flush();

bwriter.close();

breader.close();

}

列印流:單向的從程式中向外輸出資料

printwriter:列印字元流

案例: 例如 從伺服器端向 客戶端瀏覽器 輸出網頁資訊.

public static void main(string args) throws filenotfoundexception
物件輸入輸出流

物件:記憶體中的物件

為什麼要將物件輸出?

記憶體中的資料在電腦關閉,伺服器停止時資料就會消失

有時候需要將這些資料儲存起來

物件的輸出流: objectoutputstream  

物件的輸入流: objectinputstream

public static void main(string args) throws ioexception, classnotfoundexception
新建student類

/*

需要被序列化類的物件,此類必須要實現serializable介面

*/public class student implements serializable

@override

public string tostring() ';}}

public static void main(string args) throws ioexception, classnotfoundexception 

public static void main(string args) throws ioexception, classnotfoundexception

輸入輸出流(IO流

流 流 stream 的概念源於 unix 中管道 pipe 的概念,在 unix 中,管道是一條不間斷的位元組流,用來實現程式或程序間的通訊,或讀寫外圍裝置 外部檔案等。重要 1.流操作結束後必須關閉。2.inputstream reader outputstream write全是抽象,不能直接...

IO 輸入輸出流

io流 輸入流位元組輸入流 inputstream fileinputstream 構造方法 fileinputstream file file fileinputstream string filename bufferedinputstream 成員方法 int read 讀乙個位元組 int ...

輸入輸出流(IO)

outputstream,所有輸出位元組流的基類,抽象類 字元流 位元組流 編碼 解碼 writer,所有輸出字元流的基類,抽象類 什麼情況下使用字元流 如果讀寫需要編碼和解碼的資料 字元資料 這時候我們就使用字元流 轉換流的作用 可以把對應的位元組流轉換成字元流使用。將輸入控制台的一行字元資料顯示...