问题
I'm dealing with some Java code in which there's an InputStream that I read one time and then I need to read it once again in the same method.
The problem is that I need to reset it's position to the start in order to read it twice.
I've found a hack-ish solution to the problem:
is.mark(Integer.MAX_VALUE);
//Read the InputStream is fully
// { ... }
try
{
is.reset();
}
catch (IOException e)
{
e.printStackTrace();
}
Does this solution lead to some unespected behaviours? Or it will work in it's dumbness?
回答1:
As written, you have no guarantees, because mark()
is not required to report whether it was successful. To get a guarantee, you must first call markSupported(), and it must return true
.
Also as written, the specified read limit is very dangerous. If you happen to be using a stream that buffers in-memory, it will potentially allocate a 2GB buffer. On the other hand, if you happen to be using a FileInputStream
, you're fine.
A better approach is to use a BufferedInputStream
with an explicit buffer.
回答2:
You can't do this reliably; some InputStream
s (such as ones connected to terminals or sockets) don't support mark
and reset
(see markSupported). If you really have to traverse the data twice, you need to read it into your own buffer.
回答3:
It depends on the InputStream implementation. You can also think whether it will be better if you use byte[]. The easiest way is to use Apache commons-io:
byte[] bytes = IOUtils.toByteArray(inputSream);
回答4:
Instead of trying to reset the InputStream
load it into a buffer like a StringBuilder
or if it's a binary data stream a ByteArrayOutputStream
. You can then process the buffer within the method as many times as you want.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int read = 0;
byte[] buff = new byte[1024];
while ((read = inStream.read(buff)) != -1) {
bos.write(buff, 0, read);
}
byte[] streamData = bos.toByteArray();
回答5:
For me, the easiest solution was to pass the object from which the InputStream could be obtained, and just obtain it again. In my case, it was from a ContentResolver
.
来源:https://stackoverflow.com/questions/18793840/java-resetting-inputstream