Java中的InputStream和OutputStream
做Java技術好幾個月了,碰到了很多瑣碎細小的技術點,一直沒有記錄。“勿以善小而不為”,正好今天有點空,先從兩個Stream說起。
InputStream vs OutputStream
InputStream用來進行數據讀取,而OutputStream用來進行數據寫入。接口描述:
public abstract class InputStream implements Closeable {
public abstract int read() throws IOException;
public int read(byte b[]) throws IOException;
public int read(byte b[], int off, int len) throws IOException;
public long skip(long n) throws IOException;
public void close() throws IOException;
public synchronized void mark(int readlimit);
public synchronized void reset() throws IOException;
//...
}
public abstract class OutputStream implements Closeable, Flushable {
public abstract void write(int b) throws IOException;
public void write(byte b[]) throws IOException;
public void write(byte b[], int off, int len) throws IOException;
public void flush() throws IOException;
public void close() throws IOException;
}
Close Streams
Java中的Stream是需要通過close方法顯式進行關閉的。OutputStream上面還有一個方法叫flush,close方法會自動執行flush。所以在調用close之前無需調用flush方法。
如果一個Stream在構建的時候,通過構造函數傳入另外一個Stream,當該Stream被close的時候,原始的Stream也會被關閉,參見如下代碼:
OutputStream file = new FileOutputStream( "quarks.ser" );
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
try{
output.writeObject(quarks);
}
finally{
output.close();
}
派生類


有時間的話會把每個派生類簡單解釋一下。
