BufferedWriter close() method in Java with Examples
Last Updated :
28 May, 2020
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:
import java.io.*;
public class GFG {
public static void main(String[] args)
{
try {
StringWriter stringWriter
= new StringWriter();
BufferedWriter buffWriter
= new BufferedWriter(
stringWriter);
buffWriter.write(
"GEEKSFORGEEKS" , 0 , 5 );
buffWriter.close();
System.out.println(
stringWriter.getBuffer());
}
catch (Exception e) {
System.out.println(
"BufferedWriter is closed" );
}
}
}
|
Program 2:
import java.io.*;
public class GFG {
public static void main(String[] args)
{
try {
StringWriter stringWriter
= new StringWriter();
BufferedWriter buffWriter
= new BufferedWriter(
stringWriter);
buffWriter.write(
"GEEKSFORGEEKS" , 0 , 5 );
buffWriter.close();
System.out.println(
stringWriter.getBuffer());
buffWriter.write(
"GEEKSFORGEEKS" , 5 , 8 );
}
catch (Exception e) {
System.out.println(
"BufferedWriter is closed" );
}
}
}
|
Output:
GEEKS
BufferedWriter is closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close()
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...