The close() method of BufferedWriter class in Java is used to flush the characters from the buffer stream and then close it. Once the stream is closed further calling the methods like write() and append() will throw the exception.
Syntax:
public void close()
Parameters: This method does not accept any parameter.
Return value: This method does not return any value.
Exceptions: This method throws IOException if an I/O error occurs.
Below programs illustrate close() method in BufferedWriter class in IO package:
Program 1:
// Java program to illustrate // BufferedWriter close() method import java.io.*; public class GFG { public static void main(String[] args) { try { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffered writer buffWriter.write( "GEEKSFORGEEKS" , 0 , 5 ); // Close the buffered writer buffWriter.close(); System.out.println( stringWriter.getBuffer()); } catch (Exception e) { System.out.println( "BufferedWriter is closed" ); } } } |
GEEKS
Program 2:
// Java program to illustrate // BufferedWriter close() method import java.io.*; public class GFG { public static void main(String[] args) { try { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffered writer buffWriter.write( "GEEKSFORGEEKS" , 0 , 5 ); // Close the buffered writer buffWriter.close(); System.out.println( stringWriter.getBuffer()); // It will throw exception buffWriter.write( "GEEKSFORGEEKS" , 5 , 8 ); } catch (Exception e) { System.out.println( "BufferedWriter is closed" ); } } } |
GEEKS BufferedWriter is closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close()