How are the mark() and reset() methods used with InputStream classes?

Alessandro A. Garbagnati

Using the mark() and reset() method of the InputStream classes is pretty easy.
First of all you need to be sure that the InputStream that you are working with supports the mark() and reset() functionality. For this you need to use the markSupported() method.

Once you know that the stream supports those methods (when markSupport() returns true), you can use the mark(int readlimit) method to 'mark' a position in the stream. The javadoc for this method is very clear:

[...] the stream somehow remembers all the bytes read after the call to mark and stands ready to supply those same bytes again if and whenever the method reset is called. However, the stream is not required to remember any data at all if more than readlimit bytes are read from the stream before reset is called.
The reset() method will allow you to reposition the stream pointer to the position where the mark() method was called.

The following code snippet doesn't really make any sense, but it will show you how to use the markSupported(), mark() and reset() methods.

InputStream is = null;
try {
  is = new FileInputStream(new File("/tmp/testfile.tmp"));
  // check if the stream supports mark/reset methods
  if (!is.markSupported()) {
      throw new RuntimeException("Mark/Reset not supported!");
  int ch;
  int readings = 0;
  boolean marked = false;
  // read until EOF
  while ((ch = is.read()) != -1) {

    System.out.print("." + ch);

    // the first time you hit char 128, mark this position  
    if ((ch == 128) && !marked) {
      marked = true;
    // for 3 times, every time the file reaches char 200, reset
    //   and restart reading from the marked position (char 128)
    if ((ch == 200) && (readings < 3)) {
finally {
  try {
  catch (Throwable t) {
    // do nothing
To make it running you should create a file containing all the char from 0 to 255. The output should read up to 128, then for three times read the chars 129->200 and finally read the remaining.
sorry, but I haven't tested this code, but I've changed a piece of code I've used long time ago, but it should work... hopefully