Java.io.BufferedWriter.close() Method Example


Description

The java.io.BufferedWriter.close() method flushes the characters from the stream and then closes it. After closing, further write(), append() or flush() invocations will throw an IOException.

Declaration

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

public Writer close()

Parameters

NA

Return Value

This method does not return any value.

Exception

IOException − if an I/O error occurs..

Example

The following example shows the usage of public Writer close() method.

package com.tutorialspoint;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class BufferedWriterDemo {
   public static void main(String[] args) throws IOException {
      
      StringWriter sw = null;
      BufferedWriter bw = null;
      
      try{
         // create string writer
         sw = new StringWriter();
         
         //create buffered writer
         bw = new BufferedWriter(sw);
         
         // append character.
         bw.append("1");
         
         // close the writer
         bw.close();
         
         // print before appending one more character
         System.out.println(sw.getBuffer());
         
         // appending after closing will throw error
         bw.append("2");
         
         // print after appending one more character
         System.out.println(sw.getBuffer());
            
      }catch(IOException e){
         // if I/O error occurs
         System.out.print("Cannot append, buffered writer is closed");
      }finally{
         // releases any system resources associated with the stream
         if(sw!=null)
            sw.close();
         if(bw!=null)
            bw.close();
      }
   }
}

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

1
Cannot append, buffered writer is closed

java_io_bufferedwriter.htm
Advertisements