简体   繁体   English

两次读取 InputStream 的一部分

[英]Read part of an InputStream twice

I have a ServletInputStream that can be very big and I want to extract the first X bytes of the InputStream and then let the stream in it initial state.我有一个可能非常大的 ServletInputStream,我想提取 InputStream 的前 X 个字节,然后让流处于初始状态。

What I have done for now is markSupported(), mark() and reset() but the markSupported return false so I need to implement an other way of doing it.我现在所做的是 markSupported()、mark() 和 reset(),但是 markSupported 返回 false,所以我需要实现另一种方法。

A solution is described here to read an input stream twice, but the problem is that my stream can be very big in size and I can't have all of it in memory (moreover i am not sure that the max array size will be enough). 这里描述 一个解决方案来读取输入流两次,但问题是我的流的大小可能非常大,而且我不能将其全部保存在内存中(而且我不确定最大数组大小是否足够)。

Is there a way to just read a small number of bytes and then put the stream in it initial state.有没有办法只读取少量字节,然后将流置于其初始状态。 The workaround will be to consume the X bytes I want to read an then let the stream consumed pass X bytes in addition to the following process (which I want to avoid).解决方法是消耗我想要读取的 X 字节,然后让消耗的流除了以下过程(我想避免)之外传递 X 字节。

BufferedInputStream.markSupported() returns true (see Javadoc ). BufferedInputStream.markSupported()返回 true(参见Javadoc )。 Simply wrap your stream with BufferedInputStream and set a mark limit bigger than X.只需使用BufferedInputStream包装您的流并设置一个大于 X 的标记限制。

Have you looked at java.io.PushbackInputStream ?你看过java.io.PushbackInputStream吗?

If I am understanding you correctly, it seems like a good fit for what you want to achieve, especially if the bytes you want to examine are at the beginning of the stream.如果我对您的理解正确,它似乎很适合您想要实现的目标,尤其是当您要检查的字节位于流的开头时。

byte[] peekBuffer = new byte[n];
PushbackInputStream pis = new PushbackInputStream(yourStream, peekBuffer.length);

pis.read(peekBuffer);
// Examine peekBuffer

// Reinsert the peeked bytes.
pis.unread(peekBuffer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM