Taming Tiger: Formatted output Author: John Zukowski

xiaoxiao2021-03-06  85

Tam Tiger: Format Output

Let it have Printf

John Zukowski

(Jaz@zukowski.net) President, JZ Ventures, Inc. 4004

The original program of J2SE 1.4 is to include support for formatting output. These features are not added in the published version due to the time limit and this feature to decide on the new version. Now there is Tiger, which has intrinsic support for the string of the printed format.

For those who have never been exposed to C from the start of Java programming from the beginning, or those who do not know enough to C, formatted strings are some weird text strings, which specifies the output characteristics of a set of variables. Not to connect the string with the plus sign (such as firstname " lastname), but provide a string description output, and provides parameters to replace the placeholders in the string when the method call is completed: String S = String.Format ("% 1 $ S% 2 $ S", firstname, lastname).

Formatter class

First, let us analyze the new Java.util.formatter class. You may not use this class directly, but it provides the formatted internal mechanism to be performed. In this class's Javadoc, a table describing the supported formatting options will be seen. These options range from the format similar to% 7.4F, specify the accuracy and bits of the floating point number, to the% TT of formatted time, to format the third parameter% 3 $ S.

Format the output is divided into two steps: Create an Appendable object to store the output, put the contents of the format in this object with the Format () method. The implementation of the Appendable interface is listed below:

BufferedWriter ChararrayWriter Charbuffer FileWriter FilterWriter Logstream OutputStreamWriter PiredWriter PrintStream PrintWriter StringBuffer StringBuilder StringWriter Writer

When using the Formatter class, the object that implements this interface can be passed to the constructor formatter to use it as a target. Most of these classes look very similar, except for the StringBuilder class. StringBuilder is almost the same as the StringBuffer class, only one big difference: it is not a thread safe. Use StringBuilder if you know to build a string in a single thread. Use StringBuffer if the build process spans multiple threads. Listing 1 shows how usually start using formatter:

Listing 1. Typical usage of Formatter

Stringbuilder SB = New StringBuilder ();

Formatter formatter = new formatter (SB, local.us);

After creating the Formatter class, the format () method is called with formatted strings and parameters. If you need to use different Locale delivered to the constructor as part of the formatted output, you can also pass a Locale object to the Format () method. Listing 2 shows two different format ():

Listing 2. Format () method for formatter

Public Formatter Format (String Format,

Object ... ARGS)

Public Formatter Format (Locale L, String Format,

Object ... ARGS)

If you want to get a PI value of 10 digits, the code in Listing 3 will put this value into StringBuilder and print out. Printing the Formatter object will display the contents of the Appendable object.

Listing 3. Demonstrate a Formatter

Import java.util.locale;

Import java.util.formatter;

Public class build {

Public static void main (string args []) {

Stringbuilder SB = New StringBuilder ();

Formatter formatter = new formatter (SB, local.us);

Formatter.Format ("pi =% 12.10f", math.pi);

System.out.println (Formatter);

}

}

Don't forget to compile with the -source 1.5 option, otherwise the compiler does not identify the variable parameter list. This operation provides a convenient method for the formatting output and sending it to the console. We will discuss this below.

PrintStream support

A common in the PrintStream class is defined, which is used to write the System.out and System.err objects that are written to standard outputs and standard errors, respectively. TiGer introduces two new constructor (for direct writing files) and six ways to provide support for formatting (three pairs). The first pair is another version of the append () method. This pair method implements a new java.lang.Appendable interface. These methods are generally not called directly. Direct calls for format () and printf (), where the printf () version is just a convenient wrapper for the format () version, as shown in Listing 4:

Listing 4. PrintStream.Format Method

Public PrintStream Format (String Format,

Object ... ARGS)

Public PrintStream Format (Locale L,

String Format,

Object ... ARGS)

To remember the new variable parameter support, it is displayed by ... as shown in Listing 4 above.

Listing 5 demonstrates printing today's Format () method print today:

Listing 5. Examples using PrintStream.format

/

Import java.util.calendar;

Public class now {

Public static void main (string args []) {

System.out.format

"Today IS% 1 $ TB% 1 $ TE,% 1 $ TY.",

Calendar.getInstance ()

);

}

}

The output running this program is Today Is April 2, 2004. Of course, the actual output depends on the date that runs this program. The formatted string% 1 $ TB tells the program with the first parameter and print the full mine name of the Date object. Formatted Strings% 1 $ TE means the date of the month, and the formatted string% 1 $ T is the year of the four digits. Other options for printing the date are listed in the Javadoc in the Formatter object.

String support

The String class has two new Static Format () methods, and their roles are similar to the corresponding printf (). Send a format string and parameters (possibly there may be locale) and use the format conversion parameters specified in the format string. If it is the String version of this method, then the result is not the result of the String object instead of the stream. These methods are not very conspicuous, but they can avoid directly using the formatter object and create the StringBuilder in the middle. Format any object

Each of the items seen so far is to describe how to use new formatting capabilities to format existing objects and basic data. If you want to provide support for your own object with formatter, then use the FormatTable interface. By implementing a FormatTo () method shown in Listing 6 in its own class, you can use the formatted string for your own class:

Listing 6. FormatTable interface

Void Formatto (Formatter Formatter,

Int Flags,

Integer Width,

Integer Precision)

Listing 7 demonstrates using the formattable interface by providing a simple class with an NAME attribute. This name is displayed in the output that supports the width and alignment of the output.

Listing 7. FormatTable use example

Import java.util.locale;

Import java.util.formatter;

Import java.util.formattable;

Public class myObject imports formattable {

String name;

Public myObject (string name) {

THIS.NAME = Name;

}

Public void formatto

Formatter FMT,

Int f,

Integer Width,

Integer precision) {

Stringbuilder SB = New StringBuilder ();

IF (precision == null) {

// no max width

Sb.append (name);

} else if (name.length ()

Sb.append (name);

} else {

Sb.append (name.substring (0, precision - 1)). Append ('*');

}

// Apply Width and Justification

IF ((width! = null) && (sb.length ()

For (int i = 0, n = sb.Length (); i

IF ((F & formatTable.Left_justify) == formattable.left_justify) {

sb.append ('');

} else {

sb.insert (0, '');

}

}

}

FMT.FORMAT (sb.toString ());

}

Public static void main (string args []) {

MyObject my1 = new myObject ("john");

MyObject my2 = new myObject ("really long name");

// first / using toString ()

System.out.println ("First Object:" MY1); // Second / use Formatter

System.out.format ("First Object: '% s' // n", MY1);

// second / using formatter

System.out.Format ("Second Object: '% s' // n", my2);

// second / using formatter with width

System.out.Format ("Second Object: '% 10.5s' // n", my2);

// Second / use formatter with width and left justification

System.out.Format ("Second Object: '% -10.5s' // n", my2);

}

}

Running this program generates the output shown in Listing 8. The first two lines show different results using Tostring and Formatter. The width and alignment control options are displayed.

Listing 9. FormatTable Output Example

First Object: MyObject @ 10b62c9

First Object: 'John'

Second Object: 'Really Long Name'

Second Object: 'REAL *'

Second Object: 'REAL *'

Conclude

Unless it is already familiar with them by using C, you have to spend some time for all formatting options provided in Formatter. There are some small differences, but most of the behavior is very similar. An important difference on the Java platform is that it will throw an exception when the string is invalid.

Be sure to take a closer look at the available formatted strings listed in the formatter class JavaDoc. When creating your own custom class, not only a toString () implementation, but also implementing the formattable interface usually help.

转载请注明原文地址:https://www.9cbs.com/read-121947.html

New Post(0)