Java Reference
In-Depth Information
Flushing the Output Stream
You need to flush the output stream using the flush() method.
// Flus the output stream
fos.flush();
Flushing an output stream indicates that if any written bytes were buffered, they may be written to the data sink.
For example, if the data sink is a file, you write bytes to a FileOutputStream , which is an abstraction of a file. The
output stream passes the bytes to the operating system, which is responsible for writing them to the file. For a file
output stream, if you call the flush() method, the output stream passes the bytes to the operating system for writing.
It is up to the operating system when it writes the bytes to the file, If an implementation of an output stream buffers
the written bytes, it flushes the bytes automatically when its buffer is full or when you close the output stream by
calling its close() method.
Closing the Output Steam
Closing an output stream is similar to closing an input stream. You need to close the output stream using its close()
method.
// Close the output stream
fos.close();
The close() method may throw an IOException . Use a try-with-resources to create an output stream if you
want tit to be closed automatically.
Completing the Example
Listing 7-16 illustrates the steps involved in writing to a file named luci2.txt . If the file does not exist in your current
directory, the program will create it. If it exists, it will be overwritten. The file path displayed in the output may be
different when you run the program.
Listing 7-16. Writing Bytes to a File Output Stream
// SimpleFileWriting.java
package com.jdojo.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class SimpleFileWriting {
public static void main(String[] args) {
String destFile = "luci2.txt";
// Get the line separator for the current platform
String lineSeparator = System.getProperty("line.separator");
String line1 = "When she I loved look'd every day";
String line2 = "Fresh as a rose in June," ;
 
Search WWH ::




Custom Search