gpt4 book ai didi

java - 为什么 PrintStream 扩展 FilterOutputStream 而不是 OutputStream?

转载 作者:搜寻专家 更新时间:2023-11-01 03:07:24 25 4
gpt4 key购买 nike

System.outSystem.err 都是PrintStream;并且 PrintStream 扩展了 FilterOutputStream

来自 FilterOutputStream 的 javadoc:

This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality.

The class FilterOutputStream itself simply overrides all methods of OutputStream with versions that pass all requests to the underlying output stream. Subclasses of FilterOutputStream may further override some of these methods as well as provide additional methods and fields.

(强调我的)

FilterOutputStream 本身扩展了 OutputStream

我在这里不知所措。为什么 PrintStream 需要扩展 FilterOutputStream 而不是 OutputStream

感谢示例代码...

最佳答案

FilterOutputStream 应用组合模式,它将所有调用委托(delegate)给它的实例变量 out:

/* The underlying output stream to be filtered. */
protected OutputStream out;

FilterOutputStream 也有抽象类 OutputStream 的默认实现:

public void write(int b) throws IOException {
out.write(b);
}

public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}

public void write(byte b[], int off, int len) throws IOException {
if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
throw new IndexOutOfBoundsException();

for (int i = 0 ; i < len ; i++) {
write(b[off + i]);
}
}

public void flush() throws IOException {
out.flush();
}

public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
out.close();
}

现在,包括 PrintStream 在内的任何类都可以扩展 FilterOutputStream 并覆盖适当的方法。请注意,他们仍然需要将调用委托(delegate)给 out。例如 PrintStream#flush():

public void flush() {
synchronized (this) {
try {
ensureOpen();
out.flush();
}
catch (IOException x) {
trouble = true;
}
}
}

关于java - 为什么 PrintStream 扩展 FilterOutputStream 而不是 OutputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17765912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com