我可以在Java中的InputStream上执行连续的标记操作吗
我正在尝试构建一个简单的解析器,并且由于 InputStream 没有类似 peek 的方法,因此我正在使用标记和重置。 但我怀疑连续的标记调用会使之前的调用无效。是这样吗? 是否可以做类似的事情
foo.mark(1);
...
foo.mark(2);
...
foo.reset();
...
foo.reset();
如果不能,是否有其他方法来模拟这个或 peek 方法?
谢谢。
I'm trying to build a simple parser, and since InputStream doesn't have some peek-like method, I'm using mark and reset.
But I suspect that successive calls to mark, invalidate the previous ones. Is that the case?
Is it possible to do something like
foo.mark(1);
...
foo.mark(2);
...
foo.reset();
...
foo.reset();
If not, is there some other way to simulate this or the peek method?
Thx.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的怀疑是正确的, InputStream .mark(int readlimit) 方法将允许您将流重新定位到最后标记的位置,前提是您读取的字节数少于
readlimit
字节。如果您想要一个“可查看”的输入流,您可能需要考虑 PushbackInputStream。它没有明确提供查看功能,但它允许您“推回”已读取的字节。Your suspicion is correct, the InputStream.mark(int readlimit) method will allow you reposition the stream only to the last marked position, provided you have read less than
readlimit
bytes. If you want a "peekable" InputStream you may want to consider the PushbackInputStream. It doesn't explicitly offer peek functionality, but it will allow you to "push back" bytes you have read.标记不嵌套。
如果您想多次重新读取流,则可能需要将流(的一部分)复制到字节数组中,并创建一个 ByteArrayInputStream 。您仍然不能有多个标记,但可以有多个 ByteArrayInputStream 。 (或者干脆忘记 ByteArrayInputStream 并直接从数组中选取字节。)
Marks don't nest.
If you want to reread the stream several times, you might need to copy (a portion of) the stream into a byte array, and make a
ByteArrayInputStream
of it. You still can't have multiple marks, but you can have multipleByteArrayInputStream
s. (Or just forget aboutByteArrayInputStream
and pick bytes off the array directly.)