Java.io.BufferedReader.mark() Method



Description

The java.io.BufferedReader.mark(int) method marks the current position in the stream. Invoking reset() will reposition the stream to this point.

Declaration

Following is the declaration for java.io.BufferedReader.mark() method.

public void mark(int readAheadLimit)

Parameters

readAheadLimit − number of characters to be read while preserving the mark.

Return Value

The method doesn't return any value.

Exception

  • IOException − If an I/O error occurs.

  • IllegalArgumentException − If readAheadLimit is < 0.

Example

The following example shows the usage of java.io.BufferedReader.mark() method.

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderDemo {
   public static void main(String[] args) throws Exception {
      InputStream is = null; 
      InputStreamReader isr = null;
      BufferedReader br = null;

      try {
         // open input stream test.txt for reading purpose.
         is = new FileInputStream("c:/test.txt");
         
         // create new input stream reader
         isr = new InputStreamReader(is);
         
         // create new buffered reader
         br = new BufferedReader(isr);

         // reads and prints BufferedReader
         System.out.println((char)br.read());
         System.out.println((char)br.read());
         
         // mark invoked at this position
         br.mark(26);
         System.out.println("mark() invoked");
         System.out.println((char)br.read());
         System.out.println((char)br.read());
         
         // reset() repositioned the stream to the mark
         br.reset();
         System.out.println("reset() invoked");
         System.out.println((char)br.read());
         System.out.println((char)br.read());
         
      } catch (Exception e) {
         // exception occurred.
         e.printStackTrace();
      } finally {
         // releases any system resources associated with the stream
         if(is!=null)
            is.close();
         if(isr!=null)
            isr.close();
         if(br!=null)
            br.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 −

ABCDE

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

A
B
mark() invoked
C
D
reset() invoked
C
D
java_io_bufferedreader.htm
Advertisements