Java Program to mark the current position in this input stream

Java 8Object Oriented ProgrammingProgramming

The method java.io.InputStream.mark() is used to mark the current position in this input stream. This method requires a single parameter i.e. the bytes that can be read before the position marked is invalidated.

A program that demonstrates this is given as follows −

Example

import java.io.FileInputStream;
import java.io.InputStream;
public class Demo {
   public static void main(String[] args) throws Exception {
      InputStream i = null;
      try {
         i = new FileInputStream("C://JavaProgram//data.txt");
         System.out.println("Char : "+(char)i.read());
         System.out.println("Char : "+(char)i.read());
         System.out.println("Char : "+(char)i.read());
         i.mark(0);
         System.out.println("Char : "+(char)i.read());
         System.out.println("Char : "+(char)i.read());
         if(i.markSupported()){
            i.reset();
            System.out.println("Char : "+(char)i.read());
            System.out.println("Char : "+(char)i.read());
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

Char : D
Char : A
Char : T
Char : A
raja
Published on 28-Feb-2019 11:43:18
Advertisements