BufferedReader mark(int) in Java

mark(int): This method is available in the java.io.BufferedReader class of Java.

Syntax:

void java.io.BufferedReader.mark(int readAheadLimit) throws IOException

This method takes one argument. This method marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point.

Parameters: One parameter is required for this method.

readAheadLimit: Limit the number of characters that may be read while still preserving the mark.

Throws:

1. IllegalArgumentException - If readAheadLimit < 0.

2. IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReadermark {
    public static void main(String[] args) throws IOException {

        FileReader fileReader = new FileReader("D:\\hello.txt");
        BufferedReader bufferedReader =
new BufferedReader(fileReader);

        int readAheadLimit = 5;
        bufferedReader.mark(readAheadLimit);

        System.out.println("Successfully mark");

        bufferedReader.close();

    }
}

Output:

Successfully mark


Approach 2: IllegalArgumentException 

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReadermark {
    public static void main(String[] args) throws IOException {

        FileReader fileReader = new FileReader("D:\\hello.txt");
        BufferedReader bufferedReader =
new BufferedReader(fileReader);

        int readAheadLimit = -1;
        bufferedReader.mark(readAheadLimit);

        System.out.println("Successfully mark");

        bufferedReader.close();

    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Read-ahead limit < 0 at java.base/java.io.BufferedReader.mark(BufferedReader.java:495)


No comments:

Post a Comment