Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Resetting InputStream

Tags:

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?

like image 527
iMineLink Avatar asked Sep 13 '13 19:09

iMineLink


People also ask

How do you clear a stream in Java?

The flush() method of PrintStream Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream. It neither accepts any parameter nor returns any value. Parameters: This method do not accepts any parameter.

Does closing InputStreamReader close the InputStream?

Closing an InputStreamReader will also close the InputStream instance from which the InputStreamReader is reading.

What is read () in Java?

read() method reads the next byte of the data from the the input stream and returns int in the range of 0 to 255. If no byte is available because the end of the stream has been reached, the returned value is -1.

Does InputStream need to be closed?

You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.


2 Answers

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.

like image 156
kdgregory Avatar answered Sep 19 '22 04:09

kdgregory


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);
like image 26
stan Avatar answered Sep 20 '22 04:09

stan