Java Reference
In-Depth Information
Listing 7-19 is very similar in structure to Listing 7-16. It creates a
PrintStream
object using the data sink file
name. You can also create a
PrintStream
object using any other
OutputStream
object. You may notice that you do
not have to handle the
IOException
in the
catch
block because unlike another output stream, a
PrintStream
object
does not throw this exception. In addition, you use the
println()
and
print()
methods to write the four lines of text
without worrying about converting them to bytes. If you want to use auto-flush in this program, you need to create the
PrintStream
object using another constructor as in
boolean autoFlush = true;
PrintStream ps = new PrintStream(new FileOutputStream(destFile), autoFlush);
Listing 7-19.
Using the PrintStream Class to Write to a File
// FileWritingWithPrintStream.java
package com.jdojo.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class FileWritingWithPrintStream {
public static void main(String[] args) {
String destFile = "luci3.txt";
try (PrintStream ps = new PrintStream(destFile)) {
// Write data to the file. println() appends a new line
// and print() does not apend a new line
ps.println("Upon the moon I fix'd my eye,");
ps.println("All over the wide lea;");
ps.println("With quickening pace my horse drew nigh");
ps.print("Those paths so dear to me.");
// flush the print stream
ps.flush();
System.out.println("Text has been written to " +
(new File(destFile).getAbsolutePath()));
}
catch (FileNotFoundException e1) {
FileUtil.printFileNotFoundMsg(destFile);
}
}
}
Text has been written to C:\book\javabook\luci3.txt