Java Reference
In-Depth Information
9.6.2 Formatter output to a file
The following program, FormatWriteFileApp , follows closely to that
of FormatWriteApp discussed in Section 9.4.2 in which we used the
java.util.Formatter class to send formatted output to the console. How-
ever, this program sends the output to a file. The Formatter class does much of
the work. We don't even have to create a FileWriter stream as we did in the
previous section. We simply pass the File object to the Formatter constructor
and it takes care of all the output mechanics. If the file doesn't exist yet, then the
Formatter will create it, though we need to catch an exception that is thrown
in such a case.
import java.io.*;
import java.util.Formatter;
/**
* Demonstrate the java.util.Formatter capabilities for
* formatting primitive types and sending them to a file.
**/
public class FormatWriteFileApp
{
public static void main (String[] args) {
Formatter formatter = null;
File file = null;
// Get the file from the argument line.
if (args.length > 0) file = new File (args[0]);
// Else use a default file name.
if (file == null) {
System.out.println ( " Default: textOutput.txt " );
file = new File ( " textOutput.txt " );
}
// Send formatted output to the file.
try {
formatter = new Formatter (file);
}
catch (FileNotFoundException e) {
// File not found exception thrown since this is a
// new file name. However, Formatter will create
// the new file.
}
formatter.format ("Text output with Formatter. %n");
formatter.format ("Primitives converted to
strings: %n");
 
Search WWH ::




Custom Search