Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InputStream will not reset to beginning

InputStream data = realResponse.getEntity().getContent();
byte[] preview = new byte[100];
data.read(preview, 0, 100);

// Now I want to refer to the InputStream later on, but I want it from the beginning of the stream, not 100 bytes in. I tried mark() it at 100, and then reset() after I read the first 100 bytes, but that doesn't work either.

Any ideas? Probably a stupid mistake..just not seeing it.

like image 427
Du3 Avatar asked Jul 16 '11 10:07

Du3


People also ask

How do you reset InputStream?

InputStream Class reset() methodreset() method is used to reset the stream to the position marked by the mark() method most recently in this InputStream. reset() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.

How do you flush an InputStream?

InputStream cannot be flushed. Why do you want to do this? OutputStream can be flushed as it implements the interface Flushable . Flushing makes IMHO only sense in scenarios where data is written (to force a write of buffered data).

What happens if you don't close an InputStream?

resource-leak is probably more of a concern here. Handling inputstream requires OS to use its resources and if you don't free it up once you use it, you will eventually run out of resources.

Does closing Inputstreamreader close the InputStream?

close() method closes the input stream reader and invocations to read(), ready(), mark(), reset(), or skip() method on a closed stream will throw IOException.


2 Answers

When you use mark() of the java.io.InputStream object you should check with the markSupported() method if your InputStream actually support using mark. According to the API the InputStream class doesn't, but the java.io.BufferedInputStream class does. Maybe you should embed your stream inside a BufferedInputStream object like:

InputStream data = new BufferedInputStream(realResponse.getEntity().getContent());
// data.markSupported() should return "true" now
data.mark(some_size);
// work with "data" now
...
data.reset();
like image 162
Progman Avatar answered Sep 22 '22 17:09

Progman


If the InputStream supports mark (you can check with the markSupported() method), then the following should work:

InputStream data = realResponse.getEntity().getContent();
byte[] preview = new byte[100];
data.mark(100);
data.read(preview, 0, 100);
data.reset();

However, be aware that data.read(preview, 0, 100) is not guaranteed to read 100 bytes in one go, it may read less.

like image 31
Lucero Avatar answered Sep 24 '22 17:09

Lucero