Nur Aini
Nur Aini

Reputation: 393

Buffered Input Stream mark read limit

I am learning how to use an InputStream. I was trying to use mark for BufferedInputStream, but when I try to reset I have these exceptions:

java.io.IOException: Resetting to invalid mark

I think this means that my mark read limit is set wrong. I actually don't know how to set the read limit in mark(). I tried like this:

is = new BufferedInputStream(is);
is.mark(is.available());

This is also wrong.

is.mark(16);

This also throws the same exception. How do I know what read limit I am supposed to set? Since I will be reading different file sizes from the input stream.

Upvotes: 11

Views: 19468

Answers (3)

BillRobertson42
BillRobertson42

Reputation: 12883

mark is sometimes useful if you need to inspect a few bytes beyond what you've read to decide what to do next, then you reset back to the mark and call the routine that expects the file pointer to be at the beginning of that logical part of the input. I don't think it is really intended for much else.

If you look at the javadoc for BufferedInputStream it says

The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.

The key thing to remember here is once you mark a spot in the stream, if you keep reading beyond the marked length, the mark will no longer be valid, and the call to reset will fail. So mark is good for specific situations and not much use in other cases.

Upvotes: 7

Ivan Kaplin
Ivan Kaplin

Reputation: 325

This will read 5 times from the same BufferedInputStream.

for (int i=0; i<5; i++) {
   inputStream.mark(inputStream.available()+1);
   // Read from input stream
   Thumbnails.of(inputStream).forceSize(160, 160).toOutputStream(out);
   inputStream.reset();
}

Upvotes: 2

jtahlborn
jtahlborn

Reputation: 53694

The value you pass to mark() is the amount backwards that you will need to reset. if you need to reset to the beginning of the stream, you will need a buffer as big as the entire stream. this is probably not a great design as it will not scale well to large streams. if you need to read the stream twice and you don't know the source of the data (e.g. if it's a file, you could just re-open it), then you should probably copy it to a temp file so you can re-read it at will.

Upvotes: 1

Related Questions