读取输入流
我正在使用输入流从网络获取一些数据。我想创建一个日志来检查 InputStream 上是否有内容。 Log("InputStream = "+ is.read())
我得到 InputStream = 123
但后来当我使用它时,我得到InputStream = -1。我猜想这与迭代器的位置有关,但我在 Java API,您必须使用 reset()
(就像使用 mark()
时一样)才能读取再次是输入流。
I am getting some data from network using an Inputstream. I want to make a log to check if the InputStream has something on it. Log("InputStream = "+ is.read())
and I get InputStream = 123
But later when I use it I get InputStream = -1. I guess is something related with the position of the iterator, but I haven't seen in the API of Java that you have to use a reset()
(as when you use mark()
) to read again the inputStream.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正确——读给顾客听。一旦使用了流或迭代器,如果不重置它,就无法再次使用它。
Correct - one read to a customer. Once you use a stream or an iterator you can't use it again without resetting it.
InputStream
不允许“查看”下一个字符;相反,所有读取方法都会阻塞,直到数据可用为止。如果您需要查看,请使用 Java NIO。
选择器
可以告诉您是否有任何通道已准备好数据。InputStream
doesn't allow to "peek" at the next character; instead, all read methods block until data is available.If you need peeking, use Java NIO. A
Selector
can tell you if any channel has data ready.您可以将流包装在
PushbackInputStream 中
。然后你可以这样做:接下来的读取将重新读取该字符
You could wrap you stream in a
PushbackInputStream
. Then you could do this:and a following read will re-read that character
此示例使用
mark()
和reset( )
重新读取输入流,但它依赖于合适的readlimit
的先验知识。根据您的需要,它可能是一种可用的缓冲策略。This example uses
mark()
andreset()
to re-read the input stream, but it relies on a priori knowledge of a suitablereadlimit
. Depending on your needs, it may be a useable buffer strategy.