Java 日看一类(45)之IO包中的PipedWriter

该类继承自Writer类

无引入包



类头注释如下:

* Piped character-output streams.

大意如下:

管道字符型输出流



该类含有如下的成员变量:

对应的管道流输入流

private PipedReader sink;

关闭标志符

private boolean closed = false;



该类含有如下的成员方法:

构造函数(与给定的输入管道相连接

public PipedWriter(PipedReader snk)  throws IOException {
    connect(snk);
}

构造函数(默认,无连接管道

public PipedWriter() {
}

管道连接

public synchronized void connect(PipedReader snk) throws IOException {
    if (snk == null) {//检查输入管道有效性
        throw new NullPointerException();
    } else if (sink != null || snk.connected) {//检查连接状态
        throw new IOException("Already connected");
    } else if (snk.closedByReader || closed) {//检查活动情况
        throw new IOException("Pipe closed");
    }

    sink = snk;
    snk.in = -1;//初始化缓冲区指针
    snk.out = 0;
    snk.connected = true;
}

写入字符数组数据

public void write(char cbuf[], int off, int len) throws IOException {
    if (sink == null) {
        throw new IOException("Pipe not connected");
    } else if ((off | len | (off + len) | (cbuf.length - (off + len))) < 0) {
        throw new IndexOutOfBoundsException();
    }
    sink.receive(cbuf, off, len);//调用输入流的读取函数
}

刷新输出流

public synchronized void flush() throws IOException {
    if (sink != null) {//检测连接状态
        if (sink.closedByReader || closed) {//输入端活性和管道关闭情况
            throw new IOException("Pipe closed");
        }
        synchronized (sink) {
            sink.notifyAll();//唤醒所有挂起的线程(主要还是读线程,把缓冲区内容读出,写线程会自动阻塞
        }
    }
}

关闭管道连接

public void close()  throws IOException {
    closed = true;
    if (sink != null) {
        sink.receivedLast();//唤醒所有线程,修改关闭状态
    }
}




该类与PipedOutputStream类似,主要也是调用输入流的函数和方法,本体作为一个抽象出的控制模块而存在,主要功能都在PipedReader里,请先去学习该类

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章