Exactly where the output from a Formatter ends up depends on what argument you pass to the constructor. You’ve already seen the constructor that takes a filename:
public Formatter(String fileName) throws FileNotFoundException
If the named file does not exist in the current working directory, this constructor attempts to create it. If that fails for any reason other than a security violation, the constructor throws aFileNotFoundException. Security problems are reported with aSecurityExceptioninstead. If the file does exist, its contents are overwritten.
Instead of a filename, you can pass in aFileobject:
public Formatter(File file) throws FileNotFoundException
You can also use aFormatterto write onto aPrintStreamor another kind ofOutputStream:
public Formatter(PrintStream out) public Formatter(OutputStream out)
or onto anyAppendableobject:
public Formatter(Appendable out)
TheAppendableinterface is a new Java 5 interface for anything onto whichchars can be appended. This includesStringBuffers andStringBuilders. It also includes a number of classes we’ll talk about later, such asCharBuffer andWriter.
Finally, the no-args constructor creates aFormatterwith no specified destination for output:
In this case, theFormatterwrites everything onto a newStringBuilderobject. You can retrieve this object using theout()method at any time before theFormatteris closed:
public Appendable out() throws FormatterClosedException
You might need to use this method if you want to write unformatted output onto the sameStringBuilder, but more commonly you’ll just use thetoString()method to get the final result. For example: