Java.io.Writer.close() Method
Advertisements
Description
The java.io.Writer.close() method closes the stream, flushing it first. 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.
Declaration
Following is the declaration for java.io.Writer.close() method
public abstract void close()
Parameters
NA
Return Value
This method does not return a value
Exception
IOException -- If an I/O error occurs
Example
The following example shows the usage of java.io.Writer.close() method.
package com.tutorialspoint;
import java.io.*;
public class WriterDemo {
public static void main(String[] args) {
String s = "Hello World";
// create a new writer
Writer writer = new PrintWriter(System.out);
try {
// append a string
writer.append(s);
// flush the writer
writer.flush();
// append a new string
writer.append("\nThis is an example");
// flush and close the stream
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result:
Hello World This is an example