What is the writer.close() method in Java?
What is the writer object?
The writer object in Java is an instance of the Writer class. The Writer class is a class for writing to character streams.
The writer.close() method
When we create an instance of the Writer class, several methods are available. Some of these methods are close(), flush(), write(), append(), etc.
The close() or writer.close() method is used to close the writer. close() flushes and then closes the stream. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
Syntax
// create a new writer instanceWriter writer = new PrintWriter(System.out);...// call the close() methodwriter.close()
In the code above, we create a writer instance and call the close() method on it.
Parameters
This method does not accept any parameters.
Return value
None.
Code
In the example below, we create a stream, write to it, append some strings, and close the stream.
import java.io.*;class WriterDemo {public static void main(String[] args) {// create a new writerWriter writer = new PrintWriter(System.out);try {// write a string of characterswriter.write("This is Java writer.close() method");// append a stringwriter.append("\nIt is used to close a writer instance");// flush the writerwriter.flush();// append a new stringwriter.append("\nThanks for reading");// flush and close the streamwriter.close();} catch (IOException e) {System.out.println(e);}}}
Explanation
In the code above, we create a writer instance. We use try and catch to catch any errors (if errors are thrown). The writer uses the write() method to write. It then uses append() to append strings to the writer, flush() flushes the writer, and we close the writer.
Once the close() method is called, any other writer is ignored, as shown in the example below.
import java.io.*;class WriterDemo {public static void main(String[] args) {// create a new writerWriter writer = new PrintWriter(System.out);try {// write a string of characterswriter.write("This is a string");// flush and close the streamwriter.close();writer.write("This is another string");} catch (IOException e) {System.out.println(e);}}}