java.io.BufferedReader reset()

Description :

This java tutorial shows how to use the reset() method of BufferedReader class of java.io package. This method returns void and resets the stream to the latest mark. Make a note that if mark() method were not invoked prior to calling reset(), IOException will occur.

Method Syntax :

public void reset() throws IOException

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

This method returns void.

Compatibility Version :

Requires Java 1.1 and up

Exception :

IOException

The IOException will be thrown by this method is I/O error occurs. The following cases will be considered as an IOException. if the marked character is invalidated or marked as invalid, and also if the stream is not marked at all.

Java Code Example :

This java example source code demonstrates the use of delimiter() method of Scanner class. Basically it prints the delimiter that is being used by the Scanner object scan which is the default pattern since we didn’t specify delimiter to be used. The code then tokenize the String declared on the constructor of the Scanner object.

package com.javatutorialhq.java.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
 * Java example source code that uses the reset() method of
 * BufferedReader class
 * This example java program reads a user input
 * and we used the mark and reset method to go back to the marked stream
 */

public class BufferedReaderReset {

	public static void main(String[] args) {
		System.out.print("Enter Characters: ");
		// declare the BufferedReader Class
		// used the InputStreamReader to read the console input
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));

		// catch the possible IOException by the read() method
		try {
			// read characters from the stream
			System.out.println((char)reader.read());
			System.out.println((char)reader.read());
			// mark the stream
			reader.mark(1);
			System.out.println("Printing char after mark");
			System.out.println((char)reader.read());
			// reset the stream
			reader.reset();
			System.out.println("Printing characters after reset");
			System.out.println((char)reader.read());
			System.out.println((char)reader.read());
			System.out.println((char)reader.read());

			// close the BufferedReader object
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Sample Output :

Running the reset() method example source code of BufferedReader class will give you the following output

Enter Characters: 12345
1
2
Printing char after mark
3
Printing characters after reset
3
4
5

Exception Scenario :

java.io.IOException: Stream not marked
	at java.io.BufferedReader.reset(Unknown Source)
	at com.javatutorialhq.java.examples.BufferedReaderReset.main(BufferedReaderReset.java:31)

Similar Method :

  • N/A

Suggested Reading List :

References :