BufferedReader reset() in Java

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

Syntax:

void java.io.BufferedReader.reset() throws IOException

This method resets the stream to the most recent mark.

Parameters: NA

Returns: NA

Throws:

IOException - If the stream has never been marked, or if the mark has been invalidated

Approach 1: When no exception

Java

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

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

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

        int value = 10;
        bufferedReader.mark(value);
        bufferedReader.reset();
        System.out.println("Successfully reset the buffer");
        bufferedReader.close();

    }
}

Output:

Successfully reset the buffer


Approach 2: IOException 

Java

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

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

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

        bufferedReader.reset();
        System.out.println("Successfully reset the buffer");
        bufferedReader.close();

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream not marked at java.base/java.io.BufferedReader.reset(BufferedReader.java:517)


No comments:

Post a Comment