Java FileOutputStream close() Method
Example
Close a stream, then try to write to it:
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream output = new FileOutputStream("filename.txt");
output.write("Hello World".getBytes());
output.close();
try {
output.write('!');
} catch (IOException e) {
System.out.println("Error: the stream is closed.");
}
}
}
Definition and Usage
The close() method closes the stream, and releases (gives back) the file and the system resources that the stream uses.
Always close a stream when you are done writing. After the stream is closed, you cannot write to it. If you try, an IOException is thrown.
Tip: A try-with-resources statement closes the stream for you: try (FileOutputStream output = new FileOutputStream("filename.txt")) { }. See the FileOutputStream Tutorial.
Syntax
public void close()
Parameter Values
None.
Technical Details
| Throws: | IOException - if the stream cannot be closed. |
|---|
Related Pages
Java FileOutputStream Tutorial
❮ FileOutputStream Methods