Java - Reset InputStream

I am dealing with some Java code that has an InputStream that I read once, and then I need to read it again with the same method.

The problem is that I need to reset put it at the beginning to read it twice.

I found a solution to the hack-ish problem:

is.mark(Integer.MAX_VALUE); //Read the InputStream is fully // { ... } try { is.reset(); } catch (IOException e) { e.printStackTrace(); } 

Does this decision mean some kind of uncertain behavior? Or will he work in it in silence?

+8
java input stream
source share
5 answers

As it is written, you have no guarantees, because mark() not required to report whether it was successful. To get a guarantee, you must first call markSupported () and it should return true .

Also, as indicated, the specified reading limit is very dangerous. If you use a stream that buffers in memory, it potentially allocates a 2 GB buffer. On the other hand, if you use FileInputStream , you're fine.

A better approach is to use a BufferedInputStream with an explicit buffer.

+5
source share

You cannot do it reliably; some InputStream (for example, connected to terminals or sockets) do not support mark and reset (see markSupported ). If you really need to pass the data twice, you need to read it in your own buffer.

+2
source share

It depends on the implementation of InputStream. You might also wonder if it would be better to use byte []. The easiest way is to use Apache commons-io :

 byte[] bytes = IOUtils.toByteArray(inputSream); 
+1
source share

Instead of trying to reset an InputStream to load it into a buffer, such as a StringBuilder , or if it is a binary data stream a ByteArrayOutputStream . Then you can process the buffer inside 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(); 
+1
source share

For me, the easiest solution was to pass an object from which you can get an InputStream, and just get it again. In my case, it was from ContentResolver .

0
source share

All Articles