Java.io.InputStream.mark() Method

Advertisements


Description

The java.io.InputStream.mark(int readlimit) method marks the current position in this input stream. A subsequent invocation to the reset() method reposition the stream to the recently marked position.

Declaration

Following is the declaration for java.io.InputStream.mark(int readlimit) method:

public void mark(int readlimit)

Parameters

  • readlimit -- the maximum number of bytes that can be read before the mark postion becomes invalid.

Return Value

The method does not return any value

Exception

  • NA

Example

The following example shows the usage of java.io.InputStream.mark(int readlimit) method.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.InputStream;

public class InputStreamDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null;
            
      try{
         // new input stream created
         is = new FileInputStream("C://test.txt");
         
         // read and print characters one by one
         System.out.println("Char : "+(char)is.read());
         System.out.println("Char : "+(char)is.read());
         System.out.println("Char : "+(char)is.read());
                     
         // mark is set on the input stream
         is.mark(0);
         
         System.out.println("Char : "+(char)is.read());
         System.out.println("Char : "+(char)is.read());
         
         if(is.markSupported())
         {
            // reset invoked if mark() is supported
            is.reset();
            System.out.println("Char : "+(char)is.read());
            System.out.println("Char : "+(char)is.read());
         }
         
      }catch(Exception e){
         
         // if any I/O error occurs
         e.printStackTrace();
      }finally{
         
         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDEF

Let us compile and run the above program, this will produce the following result:

Char : A
Char : B
Char : C
Char : D
Char : E



Advertisements
Advertisements