Formatting Output with Class Formatter

So far, we have discussed displaying formatted output to the standard output stream. What should we do if we want to send formatted outputs to other output streams or devices, such as a JTextArea or a file? The solution relies on class Formatter (in package java.util), which provides the same formatting capabilities as printf. Formatter is a utility class that enables programmers to output formatted data to a specified destination, such as a file on disk. By default, a Formatter creates a string in memory. Figure 28.24 demonstrates how to use a Formatter to build a formatted string, which is then displayed in a message dialog.

Figure 28.24. Formatting output with class Formatter.

 1 // Fig. Fig. 28.24:
 2 // Format string with class Formatter.
 3 import java.util.Formatter;
 4 import javax.swing.JOptionPane;
 6 public class FormatterTest
 7 {
 8 public static void main( String args[] )
 9 {
10 // create Formatter and format output
11 Formatter formatter = new Formatter();
12 formatter.format( "%d = %#o = %#X", 10, 10, 10 );
14 // display output in JOptionPane
15 JOptionPane.showMessageDialog( null, formatter.toString() );
16 } // end main
17 } // end class FormatterTest

Line 11 creates a Formatter object using the default constructor, so this object will build a string in memory. Other constructors are provided to allow you to specify the destination to which the formatted data should be output. For details, see docs/api/java/util/Formatter.html.

Line 12 invokes method format to format the output. Like printf, method format takes a format string and an argument list. The difference is that printf sends the formatted output directly to the standard output stream, while format sends the formatted output to the destination specified by its constructor (a string in memory in this program). Line 15 invokes the Formatter's toString method to get the formatted data as a string, which is then displayed in a message dialog.

String static Method format

Note that class String also provides a static convenience method named format that enables you to create a string in memory without the need to first create a Formatter object. Lines 1112 and line 15 in Fig. 28.24 could have been replaced by

 String s = String.format( "%d = %#o = %#^x", 10, 10, 10 );
 JOptionPane.showMessageDialog( null, s );

Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Simiral book on Amazon © 2008-2017.
If you may any questions please contact us: