Java 中的空输入流测试
你们如何测试空的InputStream?我知道 InputStream 设计用于处理远程资源,因此在实际读取它之前,您无法知道它是否存在。我无法使用 read() 因为当前位置会改变,并且使用 mark() 并重置似乎是不合适的。
问题是,有时无法测试 read() 是否返回 -1,因为如果您有一个流并且某些第三方库使用它,则需要在将其发送到那里之前测试它是否为空。
我所说的空InputStreams是指这些new ByteArrayInputStream(new byte[0])
how do you guys test for an empty InputStream? I know that InputStream is designed to work with remote resources, so you can't know if it's there until you actually read from it. I cannot use read() because current position would change and using mark() and resetting for that seems to be inappropriate.
The problem is, that sometimes one can't test if read() returns -1, because if you have a stream and some third party library uses it, you need to test if it is empty before you send it there.
By empty InputStreams I mean these new ByteArrayInputStream(new byte[0])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将 InputStream 包装在 PushbackInputStream 中。该类会将 read() 的前几个字节存储在内部缓冲区中。您稍后可以
unread()
字节并将对象传递给第 3 方库。我不太喜欢 ByteArrayInputStream,因为它将流中的所有数据保存在内存中。
另外,在任何情况下,您都将被迫使用 read() 来检查空流,这意味着您将访问网络,至少会访问几个字节。
You can wrap your InputStream in a PushbackInputStream. This class will store the first few bytes from
read()
in an internal buffer. You can laterunread()
the bytes and pass the object to the 3rd party library.I don't really like ByteArrayInputStream, because it keeps all the data from the stream in memory.
Also, in any case, you will be forced to read() to check for the empty stream, which means you'll hit the network, at least for a few bytes.
有几个替代方案:
ByteArrayInputStreams
和其他几个类似的类根据定义是非阻塞的,因为数据已经在 VM 内存中。在这些情况下,InputStream
中的available()
可能就是您所需要的。当从程序外部的输入源(例如网络套接字、标准输入甚至文件)读取数据时,这将不起作用。如果
markSupported()
方法针对特定InputStream
实例返回 true,您可以使用mark()
和 < code>reset() 方法在尝试使用read()
后返回到流的开头。编辑:
顺便说一句,
ByteArrayInputStreams
很好地支持mark()
和reset()
,并且默认情况下它们标记在位置0
。此代码:具有以下输出:
A couple of alternatives:
ByteArrayInputStreams
and several other similar classes are by definition non-blocking, as the data is already in the VM memory. In those cases theavailable()
fromInputStream
could be what you need. This will not work when reading from an input source external to the program, e.g. a network socket, the standard input or perhaps even a file.If the
markSupported()
method returns true for a specificInputStream
instance, you may be able to use themark()
andreset()
methods to return to the start of the stream after attempting to useread()
on it.EDIT:
By the way,
ByteArrayInputStreams
supportmark()
andreset()
quite nicely and they are by default marked at position0
. This code:has this output: