Java.io.OutputStreamWriter.close() Method
Advertisements
Description
The java.io.OutputStreamWriter.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.OutputStreamWriter.close() method
public 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.OutputStreamWriter.close() method.
package com.tutorialspoint;
import java.io.*;
public class OutputStreamWriterDemo {
public static void main(String[] args) {
try {
// create a new OutputStreamWriter
OutputStream os = new FileOutputStream("test.txt");
OutputStreamWriter writer = new OutputStreamWriter(os);
// create a new FileInputStream to read what we write
FileInputStream in = new FileInputStream("test.txt");
// write something in the file
writer.write(70);
// flush the stream
writer.flush();
// read what we write
System.out.println("" + (char) in.read());
// close the stream
System.out.println("Closing Stream...");
writer.close();
System.out.println("Stream closed.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Let us compile and run the above program, this will produce the following result:
F Closing Stream... Stream closed.