Java InputStream mark() and reset()

You can use the method mark to mark a position in the inputstream and the method reset to return to that mark. It allows you to read ahead in the inputstream to determine what to do next. The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.
Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.

The following program reads in a file once and the second half of the file again using the same inputstream.

public class Main {
   public static void main(String args[]) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file.txt>");
      File file = new File(args[0]);
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
      if (bis.markSupported()) {
         int b, count=0;
         int half = (int) file.length() / 2;
         System.out.println("Complete file:");
         while ((b = > 0) {
            System.out.print((char) b);
            if (++count == half+1) 
         System.out.println("Read in second half of file again:");
         while ((b = > 0) {
            System.out.print((char) b);

To read-ahead, you can also use the PushBackInputStream.