Nam*_*man 28 java inputstream outputstream apache-commons java-11
使用Java 11,我可以初始化InputStream为:
InputStream inputStream = InputStream.nullInputStream();
Run Code Online (Sandbox Code Playgroud)
但我无法理解
ie 的潜在用例InputStream.nullInputStream或类似的API .OutputStreamOutputStream.nullOutputStream
从API Javadocs,我可以弄清楚它
返回一个新的
InputStream即读取任何字节.返回的流最初是打开的.通过调用close()方法关闭流.后续调用
close()无效.虽然流是开放的,available(),read(),read(byte[]),...skip(long),和transferTo()方法的行为都好像流的末尾已到达.
我进一步详细说明了这些说明:
有很多次我想使用需要作为目标OutputStream/Writer的参数来发送输出的方法,但是想要为其他效果静默执行这些方法.
这相当于Unix将命令输出重定向到/ dev/null,或者在DOS中将命令输出附加到NUL的能力.
然而,我无法理解陈述中声明的那些方法是什么...... 为了其他效果而默默地执行这些方法.(归咎于我没有动手使用API)
有人可以帮助我理解在可能的情况下借助示例获得这样的输入或输出流有什么用处吗?
编辑:我在进一步浏览时可以找到的类似实现之一是apache-commons'NullInputStream,它更好地证明了测试用例的合理性.
Mil*_*Bem 19
有时您希望拥有InputStream类型的参数,但也可以选择不使用任何数据提供代码.在测试中,它可能更容易模拟它,但在生产中你可以选择绑定空输入而不是用ifs和标志散布你的代码.
相比:
class ComposableReprinter {
void reprint(InputStream is) throws IOException {
System.out.println(is.read());
}
void bla() {
reprint(InputStream.nullInputStream());
}
}
Run Code Online (Sandbox Code Playgroud)
有了这个:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
或这个:
class NullableReprinter {
void reprint(InputStream is) throws IOException {
if (is != null) {
System.out.println(is.read());
}
}
void bla() {
reprint(null);
}
}
Run Code Online (Sandbox Code Playgroud)
输出恕我直言更有意义.输入可能更符合一致性.
这种方法称为Null Object:https://en.wikipedia.org/wiki/Null_object_pattern
And*_*lko 12
我认为它是一个更安全(1)和更具表现力的(2)替代初始化流变量null.
[Output|Input]Stream是一种抽象.为了返回null/empty/mock流,您必须将核心概念偏离到特定实现.| 归档时间: |
|
| 查看次数: |
927 次 |
| 最近记录: |