Java Print Streams - Formatter
(Page 5 of 5 )
In fact, printf() is a little more general than System.out (though that’s its primary justification). Besides printf(), the PrintStreamclass also has aformat()method:
public PrintStream format(String format, Object... args)
This does exactly the same thing asprintf(). That is, the previous example could be rewritten like this and produce identical output:
for (double degrees = 0.0; degrees < 360.0; degrees++) {
double radians = Math.PI * degrees / 180.0;
double grads = 400 * degrees / 360;
System.out.format("%5.1f %5.1f %5.1f\n", degrees , radians, grads);
}
Why two methods, then? Theformat()method is used not just byPrintStreambut also by thejava.util.Formatterclass:
public class Formatter implements Flushable, Closeable
printf()is there solely to make C programmers feel nostalgic.
Formatteris the object-oriented equivalent ofsprintf()andfprintf()in C. Rather than writing its output onto the console, it writes it into a string, a file, or an output stream. Pass the object you want to write into to theFormatterconstructor. For example, this code fragment creates aFormatterthat writes data into a file named angles.txt:
Formatter formatter = new Formatter("angles.txt");
Once you’ve created aFormatterobject, you can write to it using theformat()method just as you would withSystem.out.format(), except that the output goes into the file rather than onto the console:
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);
}
Formatters are not output streams, but they can and should be flushed and closed just the same:
formatter.flush();
formatter.close();
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
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.
|
|