標籤:
現實世界中我們總要處理不同的資料來源:
- 位元組數組。
- String對象
- 檔案。
- “管道”,工作方式與實際管道相似。
- 一個有其他種類組成的序列。
- 其他資料來源,如Interent串連等。 --From 《Java編程思想》
對於以上的資料來源,Java io都提供了相對應的流處理類,如讀取檔案資料來源FileInputStream,FileOutputStream,這些類都繼承了InputStream這個抽象類別,並重新實現了主要的介面。作為Java io的學習篇,這裡主要分析了面向位元組的io和面向字元的io。
面向位元組
面向位元組顧名思義他們在處理資料流時,是以位元組為單位的。這些流處理類繼承了InputStream和OutputStream兩個抽象類別。下面簡單看下這兩個父類具有的介面
InputStream
public abstract int read()/*從輸入資料流中讀取相同個位元組到b中,返回實際讀取位元組的個數,可能小於b的長度*/public int read(byte b[])/*讀取最多len個位元組到位元組數組b中,且讀取的第一個自己存放在b[off],返回實際讀取的位元組個數*/public int read(byte b[], int off, int len)/*從輸入資料流中跳過n位元組,返回實際跳過的位元組長度*/public long skip(long n)/*標記當前輸入資料流的位置,結合reset函數使用,readlimit參數指明在mark失效之前,可從流中讀取的位元組長度*/public synchronized void mark(int readlimit)public synchronized void reset()/*查看是否支援mark功能*/public boolean markSupported()
以上是InputStream所具有的介面,最主要的函數功能便是從流中讀取資料,其子類都該函數都有各自實現。為繼承了InputStream的一些子類(僅存在於io包內的類),其中FilterInputStream是一個裝飾器類,他持有一個InputStream對象,所以繼承了FilterInputStream的類可以添加其他的功能。這就是為什麼我們經常會用到將各種流組合使用的原因。
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("")));
OutputStream
/*將b的低8位寫到輸出資料流中*/public abstract void write(int b) throws IOException/*將b位元組數組寫到輸出資料流中*/public void write(byte b[]) throws IOException/*以off為b的起點,將len個長度的位元組寫入到輸出資料流中*/public void write(byte b[], int off, int len) throws IOException
可以看到OutputStream的介面就是將位元組寫入到輸出資料流中,對於不同的資料來源OutputStream同樣有相應的子類。類似於FilterInputStream,FilterOutputStream同樣是一個裝飾器類以組合其他的流實現不同的功能。另外,我們常用的System.out對象就是一個PrintStream執行個體。
下面簡單介紹下一些類的作用:
ByteArrayInputStream/ByteArrayOutputStream從緩衝區位元組數組中讀取到流/將流寫到緩衝區位元組數組(一種資料來源)。
FileInputStream/FileOutputStream從檔案讀取資料到流/或將流寫到檔案中(資料來源),經常搭配FileOutputStream使用。
DataInputStream/DataOutputStream以可移植的方式從流長讀取/寫入基本類型資料(int,char,long)。
BufferedInputStream/BufferedOutputStream每次讀取/寫入緩衝區(預設8k),避免每次進行實際操作,提高效率。
一個深拷貝的輸入輸出資料流樣本,寫入到byte數組中,同樣也可以寫入到其他流中:
public Object deepCopy() throws Exception{ //ByteArrayOutputStream ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(this); //讀出二進位流產生的新對象 ByteArrayInputStream ba = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(ba); return oi.readObject();}面向字元
以字元為單位處理流,有輸入資料流抽象類別Reader、輸出資料流抽象類別Writer。Reader、Writer並不能完全取代InputStream、OutputStream,但能更方便的對文本和字元類型的資料進行操作(支援Unicode,java的char是Unicode的)。Reader、Writer有類似於InputStream、OutputStream的介面,主要就是將byte操作改變成char操作,就不一一列出。
Reader:
protected Object lock;public int read(java.nio.CharBuffer target) throws IOException
Reader提供了一個lock鎖屬性,和read到CharBuffer的操作。lock預設是Reader對象本身(this),這樣SubClass便可以使用這個對象來同步流的操作,這能達到更細粒度的同步操作(以後學習線程同步再來詳細介紹,這裡就先忽略)。同樣CharBuffer在學習nio再來介紹。
來看一下Reader的繼承結構:
大多數類都與Stream類相對應,就不詳細解釋具體用法了。需要注意打是,InputStreamReader使用StreamDecoder類可以將位元組流轉換到字元流,所以有如下用法:
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
Writer:
private char[] writeBuffer;protected Object lock;abstract public void write(char cbuf[], int off, int len) throws IOException;public void write(String str, int off, int len) throws IOException/*相當於write(csq.toString())*/public Writer append(CharSequence csq) throws IOException
Writer增加了一些對String和CharSequence的寫操作,writeBuffer用來暫時存放要被寫入流的字串或字元數組,其餘的介面類似於OutputStream。Writer的類繼承結構如下:
還是直接舉一些流操作的例子,這些例子來自《Java編程思想》。這些流類需要結合使用,才能發揮其最大的功能
public class BufferedInputFile { public static void main(String[] args) { //System.out.print(read("BufferedInputFile.java")); //memoryInput(read("BufferedInputFile.java")); //basicFileOut("BufferedInputFile.java"); storingAndRecoveringData(); } //緩衝輸入檔案 public static String read(String file) { BufferedReader bReader; StringBuilder sb = new StringBuilder(); try { bReader = new BufferedReader(new FileReader(file)); String s; while((s=bReader.readLine()) != null){ sb.append(s + "\n"); } bReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb.toString(); } //記憶體輸入 public static void memoryInput(String str){ try { StringReader srReader = new StringReader(str); int c; while((c=srReader.read()) != -1) System.out.print((char)c); srReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //格式化的記憶體輸入 public static void formattedMemoryInput(byte[] b){ DataInputStream in = new DataInputStream( new ByteArrayInputStream(b)); try { while(in.available() != 0) //慎用available讀取媒介不用,實現不同 System.out.print((char)in.readByte()); in.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("end"); } } //基本檔案輸出, 實際上檔案輸出常使用bufferedwriter,以得到更好的效能 public static void basicFileOut(String file){ try { BufferedReader in = new BufferedReader(new FileReader(file)); PrintWriter pWriter = new PrintWriter(new FileWriter("test.txt")); int lineCount = 1; String string = ""; while((string=in.readLine()) != null) pWriter.println(lineCount++ + ":" + string); pWriter.close(); in.close(); System.out.print(read("test.txt")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //儲存和恢複資料 DataOutputStream DataInputStream結合使用可以保證準確的讀取資料 public static void storingAndRecoveringData(){ try { DataOutputStream outputStream = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("data.txt"))); outputStream.writeDouble(3.1415926); outputStream.writeUTF("what a f"); outputStream.writeUTF("hello world"); outputStream.close(); DataInputStream in = new DataInputStream(new FileInputStream("data.txt")); System.out.println(in.readDouble()); System.out.println(in.readUTF()); System.out.println(in.readUTF()); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}RandomAccessFile
RandomAccessFile適用於大小已知的記錄組成的檔案,可以使用seek()方法將記錄轉移。RandomAccessFile僅實現了DataInput和DataOutput介面(故有很多readDouble(),writeDouble()等操作),與InputStream和OutputStream沒有關係。
在JDK1.4中,RandomAccessFile的大多數功能被nio儲存對應檔取代。
看一個實際操作例子:
public static void usingRandomAccessFile(String file){ try { RandomAccessFile rFile = new RandomAccessFile(file, "rw"); //rw讀寫 for(int i=0; i<7; ++i){ rFile.writeDouble(i*1.414); } rFile.writeUTF("end"); rFile.close(); display(file); rFile = new RandomAccessFile(file, "rw"); rFile.seek(5*8); rFile.writeDouble(47.000144); rFile.close(); display(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}public static void display(String file) throws IOException { RandomAccessFile rFile = new RandomAccessFile(file, "r"); //r僅讀 for (int i = 0; i < 7; ++i) { System.out.println("value " + i + ": " + rFile.readDouble()); } System.out.println(rFile.readUTF()); rFile.close();}public static void main(String[] args) { usingRandomAccessFile("hh.txt");}
OUTPUT
value 0: 0.0
value 1: 1.414
value 2: 2.828
value 3: 4.242
value 4: 5.656
value 5: 7.069999999999999
value 6: 8.484
end
value 0: 0.0
value 1: 1.414
value 2: 2.828
value 3: 4.242
value 4: 5.656
value 5: 47.000144
value 6: 8.484
end
Java I/O解析