天天看點

InputStream\OutputStream\Reader\Writer

InputStream\OutputStream\Reader\Writer構成了java.io的鼻祖。

具體如下:

InputStream和OutputStream類僅僅讀取和寫入單個的位元組和位元組數組,它們沒有讀取和

寫入字元串和數值的方法。

對于Unicode文本,一個字元占用兩個位元組,是以出現了Reader和Writer。

特别:ZipInputSteam和ZipOutputStream能讀寫常見的ZIP壓縮格式的檔案。

InputStream、OutputStream、Reader、Writer類都實作了Closeable接口。

OutputStream和Writer都實作了Flushable接口。

FileInputStream和FileOutputStream能夠把輸入和輸出流與磁盤檔案關聯起來。

eg:

FileInputStream fin = new FileInputStream("c:\\dev\\my.dat");------注意:最好使用反斜杠,反斜杠代表轉義符使用。

或者:

File f = new File("c:\\dev\\my.dat');

FileInputStream fin = new FileInputStream (f);

用于讀取位元組:

byte b = (byte)fin.read();

用于讀取數值:

DataInputStream dis = new DataInputStream(fin);

double d = dis.readDouble();

FileInputStream沒有讀取數值的能力,但是DataInputStream也沒有從檔案中讀取數值的方法,是以兩者注定在一起結合使用!

從上面我們可以知道:

java的處理IO的兩種政策:一些流(如FileInputStream)可以從檔案及其他地方接收位元組;另一些流(如DataInputStream和PrintWriter)可以将位元組組合成更加有用的資料類型。

eg:

FileInputStream fin = new FileInputStream("c:\\dev\\my.dat");---------從檔案中讀取值,建立流

DataInputStream dis = new DataInputStream(fin); --------結合後的流叫:過濾流(filtered stream)

double d = dis.readDouble();

預設情況下,流是不能進行緩沖處理的。就是每次對流進行read讀取都要求作業系統發送一個新位元組,若想要對目前目錄下的檔案

進行緩沖和資料輸入操作,應該利用FileInputStream和FileOutputStream它們的子類合并為一個新的過濾流。

DataInputStream dis= new DataInputStream(new BufferedInputStream(new FileInputStream("c:\\dev\\my.dat")));

PushbackInputStream pis = new PushbackInputStream(new BufferedInputStream(new FileInputStream("c:\\dev\\my.dat")));-------能夠對流進行跟蹤,如下:

int b = pis.read(); -----讀取下一個位元組

if(b != '<') pis.unread(b);--------不是自己想要的,把它扔回去

但是read和unread是PushbackInputStream僅有的方法,若既想預檢視,又想擷取值,可以用:

DataInputStream dis= new DataInputStream(

pis = new PushbackInputStream(new BufferedInputStream(new FileInputStream("c:\\dev\\my.dat")));

利用構造的真正實用的流序列,也為我們帶來很大的靈活性。

處理zip檔案:

ZipInputStream zip = new ZipInputStream(new FileInputStream("ocean.zip"));

DataInputStream dis = new DataInputStream(zip);