java.io.BufferedReader close()

Description :

This java tutorial shows how to use the close() method of BufferedReader class of java.io package. This method returns void and closes the stream thus further invocation of read(), ready(), readLine(), mark(), reset(), and skip() will result to IOException.

Method Syntax :

public void close() throws IOException

Parameter Input :

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

Method Returns :

This method returns void and closes the stream for further reading.

Compatibility Version :

Requires Java 1.1 and up

Exception :

None

Discussion :

The scanner close() is used to make sure that there is no memory leak happen on our program. And also most importantly to recover memory allocation allotted for this BufferedReader object. This will tell the JVM that this BufferedReader object is ready for garbage collection.

Java Code Example :

This java example source code demonstrates the use of close() method of the BufferedReader class. Basically we just read the user input from the console and then we close the reader using the close() method.

package com.javatutorialhq.java.examples;

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

/*
 * Java example source code that uses the close() method of BufferedReader
 */

public class BufferedReaderClose {

	public static void main(String[] args) {
		System.out.print("Who are you? ");
		// declare the BufferedReader Class
		// used the InputStreamReader to read the console input
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));
		String readVal;
		// catch the possible IOException
		try {
			// assign the return value of the readLine() method to a variable
			readVal = reader.readLine();
			// print the text read by the BufferedReader
			System.out.println("Name:" + readVal);			
			// close the BufferedReader object
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

} 

Sample Output :

Running the close() method example source code of Scanner class will give you the following output

java BufferedReader close() method example

java BufferedReader close() method example

Exception Scenario :

java.io.IOException: Stream closed
	at java.io.BufferedReader.ensureOpen(Unknown Source)
	at java.io.BufferedReader.read(Unknown Source)
	at com.javatutorialhq.java.examples.BufferedReaderClose.main(BufferedReaderClose.java:28)

Similar Method :

  • N/A

Suggested Reading List :

References :