Formatters and Java Print Streams (Page 1 of 5 )
Last week, we discussed Java print streams, concluding with the format method and formatter objects. This week, we pick up from where we left off. This is the second part of a three-part sereis. It is excerpted from chapter seven of
Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Constructors
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:
public Formatter()
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:
Formatter formatter = new Formatter();
for (double degrees = 0.0; degrees < 360.0; degrees++) {
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
formatter.format("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
}
String table = formatter.toString();
Next: Character Sets >>
More Java Articles
More By O'Reilly Media
|
This article is excerpted from chapter seven of Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Check it out today at your favorite bookstore. Buy this book now.
|
|