gpt4 book ai didi

java - Java 中 null(Input/Output)Stream API 的用例是什么?

转载 作者:IT老高 更新时间:2023-10-28 21:12:44 24 4
gpt4 key购买 nike

使用 Java 11,我可以将 InputStream 初始化为:

InputStream inputStream = InputStream.nullInputStream();

但我无法理解 InputStream.nullInputStream 的潜在用例或 OutputStream 的类似 API 即OutputStream.nullOutputStream .

从 API Javadocs,我可以弄清楚它

Returns a new InputStream that reads no bytes. The returned stream is initially open. The stream is closed by calling the close() method.

Subsequent calls to close() have no effect. While the stream is open, the available(), read(), read(byte[]), ... skip(long), and transferTo() methods all behave as if end of stream has been reached.

我通过了detailed release notes进一步说明:

There are various times where I would like to use methods that require as a parameter a target OutputStream/Writer for sending output, but would like to execute those methods silently for their other effects.

This corresponds to the ability in Unix to redirect command output to /dev/null, or in DOS to append command output to NUL.

但我无法理解语句中的 那些方法 是什么,如 .... 静默执行这些方法以获得其他效果。 (怪我缺乏对 API 的实际操作)

如果可能的话,有人可以通过示例帮助我了解拥有这样的输入或输出流有什么用处吗?


编辑:我在进一步浏览时可以找到的类似实现之一是 apache-commons' NullInputStream ,这确实更好地证明了测试用例的合理性。

最佳答案

有时您希望有一个 InputStream 类型的参数,但也希望能够选择不向您的代码提供任何数据。在测试中模拟它可能更容易,但在生产中您可以选择绑定(bind) null input 而不是使用 if 和标志分散代码。

比较:

class ComposableReprinter {
void reprint(InputStream is) throws IOException {
System.out.println(is.read());
}

void bla() {
reprint(InputStream.nullInputStream());
}
}

用这个:

class ControllableReprinter {
void reprint(InputStream is, boolean for_real) throws IOException {
if (for_real) {
System.out.println(is.read());
}
}
void bla() {
reprint(new BufferedInputStream(), false);
}
}

或者这个:

class NullableReprinter {
void reprint(InputStream is) throws IOException {
if (is != null) {
System.out.println(is.read());
}
}
void bla() {
reprint(null);
}
}

恕我直言,输出更有意义。输入可能更多是为了保持一致性。

这种方法称为Null Object:https://en.wikipedia.org/wiki/Null_object_pattern

关于java - Java 中 null(Input/Output)Stream API 的用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448840/

24 4 0