該類是輸出流的“鼻祖”,所有的輸出流都繼承了該類
該類完成了Closeable,Flushable接口
無引入其他包
該類的類頭註釋如下:
/** * This abstract class is the superclass of all classes representing * an output stream of bytes. An output stream accepts output bytes * and sends them to some sink. * <p> * Applications that need to define a subclass of * <code>OutputStream</code> must always provide at least a method * that writes one byte of output. * * @author Arthur van Hoff * @see java.io.BufferedOutputStream * @see java.io.ByteArrayOutputStream * @see java.io.DataOutputStream * @see java.io.FilterOutputStream * @see java.io.InputStream * @see java.io.OutputStream#write(int) * @since JDK1.0 */
大意如下:
該抽象類是所有byte輸出流的頂級類
一個輸出流接收需要輸出的bytes然後發送到底層
應用需要去聲明該類的子類,並且必須至少提供用於寫出一個byte的方法
該類含有如下的成員方法:
寫出一個byte(必須被子類提供)
public abstract void write(int b) throws IOException;
寫出一個byte數組
public void write(byte b[]) throws IOException { write(b, 0, b.length); }
寫出byte數組中的特定位置和長度的byte
public void write(byte b[], int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if ((off < 0) || (off > b.length) || (len < 0) ||//判定數組下標有效性 ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } for (int i = 0 ; i < len ; i++) {//循環調用寫出一個byte的方法 write(b[off + i]); } }
刷新流(該類會強制流中的緩存數據立即被寫出,一般也是這麼用,寫了一些東西,差不多就flush。該方法只能保證將數據提交給操作系統,不能保證數據被寫到物理介質上(當輸出目標爲操作系統提供的抽象概念時,如文件))
public void flush() throws IOException { }
關閉流
public void close() throws IOException { }
該類的結構基本就是所有輸出類的大體結構,其他輸出流在此基礎上進行擴充,例如buffer類添加了緩衝區,writer提供了轉碼,Filter提供了雙層輸出流來進行過濾(內含實際的輸出流,外部封包了一層)
Closeable該類繼承自AutoCloseable類
引入瞭如下包(我也不知道爲啥在同一個包內需要import,估計是寫錯了)
import java.io.IOException;
該類類頭註釋如下:
/** * A {@code Closeable} is a source or destination of data that can be closed. * The close method is invoked to release resources that the object is * holding (such as open files). * * @since 1.5 */
大意如下:
Closeable標識了可以被關閉數據源或者目標
close方法被調用來釋放被該對象掌控的資源(例如打開的文件)
該類含有如下的成員方法:
關閉當前對象,釋放資源(在流已經關閉的情況下不產生任何影響。該方法在某些特定情況下可能會調用失敗,拋出IO異常。在這種情況下強烈建議先放棄底層資源,在IOException被拋出前內部關閉(特定情況見AutoCloseable))
public void close() throws IOException;
該類被幾乎所有輸入輸出類繼承,效果和作用也十分清晰。只是在報錯的時候需要注意出現的是哪種特殊情況,同時並處理Close失敗的異常。