18
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.

Mubashar
  • 12,300
  • 11
  • 66
  • 95
Du3
  • 1,424
  • 6
  • 18
  • 36

2 Answers2

26

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();
Progman
  • 16,827
  • 6
  • 33
  • 48
  • https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#reset "the reset() method in InputStream does nothing other than throw IOException()" ;-) – Chris Huang-Leaver Sep 21 '16 at 02:07
1

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.

Lucero
  • 59,176
  • 9
  • 122
  • 152
  • I cannot answer this without knowing what the `realResponse` class is (and which version of the library it is in). – Lucero Jul 16 '11 at 10:49