Java - BufferedReader close() method



Description

The Java BufferedReader Close() method closes the stream and releases any system resources associated with it. After the closing of the stream, read(), ready(), mark(), reset(), or skip() invocation will throw IOException.

Declaration

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

public void close()

Parameters

NA

Return Value

This method does not return any value.

Exception

IOException − If an I/O error occurs.

Assumption

Assuming we have a text file example.txt, which has the following content. This file will be used as an input for our example programs −

ABCDE

Example - Using close() method

The following example shows the usage of Java BufferedReader close() method.

BufferedReaderDemo.java

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
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 example.txt for reading purpose.
         is = new FileInputStream("example.txt");
         
         // create new input stream reader
         isr = new InputStreamReader(is);
         
         // create new buffered reader
         br = new BufferedReader(isr);
         
         // releases any system resources associated with reader
         br.close();
         
         // creates error
         br.read();
         
      } catch(IOException e) {
         // IO error
         System.out.println("The buffered reader is closed. " + e.getMessage());
      } finally {
         // releases any system resources associated
         if(is!=null)
            is.close();
         if(isr!=null)
            isr.close();
         if(br!=null)
            br.close();
      }
   }
}

Output

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

The buffered reader is closed. Stream closed

Example - Closing a BufferedReader After Reading from a File

The following example shows the usage of Java BufferedReader close() method.

BufferedReaderDemo.java

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderDemo {
   public static void main(String[] args) {
      BufferedReader reader = null;
      try {
         // Input string
         String input = "Hello, World!\nWelcome to the BufferedReader"+
            "example.\nThis is line 3.";
         // Initialize BufferedReader with StringReader
         reader = new BufferedReader(new StringReader(input));
         // Read and print the string content line by line
         String line;
         while ((line = reader.readLine()) != null) {
            System.out.println(line);
         }
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      } finally {
         // Close the BufferedReader to release resources
         try {
            if (reader != null) {
               reader.close();                     
               System.out.println("BufferedReader closed successfully.");
            }
         } catch (IOException e) {     
            System.err.println("Error while closing BufferedReader: " +           
            e.getMessage());
         }
      }
   }
}

Output

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

Hello, World!
Welcome to the BufferedReader example.
This is line 3.
BufferedReader closed successfully.

Explanation

  • The BufferedReader is initialized using a StringReader to read an input String.

  • Inside the try block, the readLine() method reads the file line by line until it reaches the end (null).

  • The close() method is called in the finally block to ensure the BufferedReader is closed regardless of whether an exception occurs or not.

Example - Using BufferedReader with try-with-resources

The following example shows the usage of Java BufferedReader close() method.

BufferedReaderDemo.java

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderDemo {
   public static void main(String[] args) {
      // Input string 
      String input = "Hello, World!\nWelcome to the BufferedReader example.\nThis is line 3."; 
      String line;
      // Using try-with-resources for automatic resource management 
      try (BufferedReader reader = new BufferedReader(new StringReader(input))) { 
         // Read and print the string content line by line String line;            
         while ((line = reader.readLine()) != null) {
            System.out.println(line); 
         }
      }
      catch (IOException e) { 
         System.err.println("An error occurred: " + e.getMessage());
      }   
   }
}

Output

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

Hello, World!
Welcome to the BufferedReader example.
This is line 3.

Explanation

  • The BufferedReader is declared inside the parentheses of the try-with-resources statement.

  • In this approach, the BufferedReader is automatically closed at the end of the try block, even if an exception occurs. This eliminates the need for an explicit finally block to close the reader.

  • This method is more concise and reduces boilerplate code while ensuring proper resource management.

All examples demonstrate how to use the close() method, with the last approach being preferred due to its simplicity and automatic resource management.

java_io_bufferedreader.htm
Advertisements