SCJP Study Guide:
API Contents


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
PrintWriter

Formatted Output


Overview


J2SE 5.0 introduces a new way to format output that is similar to that of the C language's printf. In this approach, each argument to be formatted is described using a string that begins with % and ends with the formatted object's type. So now you can use System.out.printf() to send formatted numerical output to the console. It uses a java.util.Formatter object internally and so emulates the printf() function in C.

It's likely that you will most often use the new formatting approach in a call similar to either of the following:

   System.out.format("Pi is approximately  %f", Math.Pi);
   System.out.printf("Pi is approximately  %f", Math.Pi);

There is no difference between System.out.format() and System.out.printf(). System.out is an instance of java.io.PrintStream. The PrintStream class contains the definition of the common System.out and System.err objects for writing to standard output and standard error, respectively.

PrintStream, java.io.PrintWriter, and java.lang.String each have four new public methods:

format( String formatString, Object... args);
printf( String formatString, Object... args);
format( Locale locale, String formatString, Object... args);
printf( Locale locale, String formatString, Object... args);

where formatString is a String with a placeholder for formatted values to be substituted, and values to be substituted are listed as further parameters in sequence.  All the placeholders start with '%'.  After the '%' comes at least one conversion character describing the form of the value substituted.  These characters are limited to: %b, %c, %d, %f, %s for the SCJP exam object:

  • %b - If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true". For example:

System.out.printf("Value =|%3.2b|%n", null);
System.out.printf("Value =|%3.2b|%n", ""); 
System.out.printf("Value =|%.2b|%n", null); 
System.out.printf("Value =|%.2b|%n", ""); 
System.out.printf("Value =|%3b|%n", -1); 
System.out.printf("Value =|%3b|%n", 1.2); 

Output:
Value =| fa|
Value =| tr|
Value =|fa|
Value =|tr|
Value =|true|
Value =|true|
  • %c - The result is a Unicode character.

System.out.printf("Value =%c%n", 44.3);
//runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%c%n", (int)44.3);//OK "Value =,"
System.out.printf("Value =%c%n", "A");
//runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%.3c%n", 'a');
//runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =|%c|%n", 'a');
//OK "Value =|a|"
System.out.printf("Value =|%3c|%n", 'a');
//OK "Value =|  a|"
  • %d - The result is formatted as a decimal integer. For example:

System.out.printf("Value =%d%n", 44.4227); 
// runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%d%n", (int)44.4227);
//OK "Value =44"
System.out.printf("Value =%.3d%n", 44.4227);
// runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%.3d%n", (int)44.4227);
// runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%3.3d%n", 44.4227);
// runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%3.3d%n", (int)44.4227);
// runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%d%n", "sss");
// runtime exception : java.util.IllegalFormatConversionException
  • %f - The result is formatted as a decimal number.

System.out.printf("Value =%f%n", 44);  
//runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%f%n", true); 
//runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%f%n", "C");  
//runtime exception : java.util.IllegalFormatConversionException
System.out.printf("Value =%f%n", (float)44);
//OK "Value =44.000000"
System.out.printf("Value =|%.3f|%n", 44.4227);
//OK "Value =|44.423|"	
System.out.printf("Value =|%10.3f|%n", 44.4227);
//OK "Value =|    44.423|"
  • %s - If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().

System.out.printf("Value =|%3.3s|%n", 44.53333);
System.out.printf("Value =|%3s|%n", true);
System.out.printf("Value =|%3.2s|%n", true);
System.out.printf("Value =|%.2s|%n", true);
System.out.printf("Value =|%s|%n", "SCJP");
Output:
Value =|44.|
Value =|true|
Value =| tr|
Value =|tr|
Value =|SCJP|

Format string syntax provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output.

There are also special conversions for dates and times. The general form of the specifier includes several optional terms:

  %[argument_index$][flags][width][.precision]conversion

The argument_index indicates to which argument the specifier applies. For example, %2$ indicates the second argument in the list.

For example, we would like to print out different precision of PI. You can use the following code

System.out.printf("PIs = %5.3f %5.5f %5.10f", Math.PI, Math.PI, Math.PI);
output:
PIs = 3.142 3.14159 3.1415926536

with argument_index, we can rewrite the above statement

System.out.printf("PIs = %1$5.3f %1$5.5f %1$5.10f", Math.PI);
output:
PIs = 3.142 3.14159 3.1415926536

where the %1$5.3f formatting string in the code above tells the program to use the first argument and print out the Math.PI with 5.3f format. The %1$5.5 formatting string means to display use the first argument and print out the Math.PI with 5.5f format, and so on.

A flag indicates an option for the format. For example, '+' requires that a sign be included and '0' requires padding with zeros.

System.out.printf("PI = %+5.10f %n", Math.PI);
System.out.printf("TEN = %+05d %n", 10);
Output:
PI = +3.1415926536 
TEN = +0010 

The width indicates the minimum number of characters and the precision is the number of places for the fraction. With any type you can specify a minimum   field width via an integer right after the %.  For example:

System.out.printf("PI = %5.10f", Math.PI);
Output:
PI = 3.1415926536

In the example, the format string includes the specifier "%5.10f" that is applied to the argument. The '%' sign signals a specifier. The width value 5 requires at least five characters for the number, the precision value 10 requires ten places in the fraction, and the conversion symbol 'f' indicates a decimal representation of a floating-point number.

What does the "width" indicate? Let's see the following example:

System.out.printf("Value =%.3f%n", 44.4227);
System.out.printf("Value =%4.3f%n", 44.4227);
System.out.printf("Value =%10.3f", 44.4227);
output:
Value =44.423
Value =44.423
Value =    44.423 

All of three cases, the numbers are not just truncated. The value of 44.4227 is rounded off to three decimal places. In the third case, the leading spaces are inserted because you specified that the number should use ten characters,even though the precision restricts it to using only three characters and a decimal place. Such as field 10 characters; string 6 characters; 10-4 =  4 leading space.

  • A number right after the % gives the minimum field width NOT the number of blanks to add.
  • Do not forget to count any decimal point in the total field width.  A decimal point is a character.

There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas"\n " is not.

There are several format placeholders that refer to explicit values, and do not correspond to a value later in the parameter list.  For example:
   %%  means just %.
   %n means a line-break or newline, appropriate to the current operating system.

Notes

For general argument types, the precision is the maximum number of characters to be written to the output.

For the floating-point conversions 'e', 'E', and 'f' the precision is the number of digits after the decimal separator. If the conversion is 'g' or 'G', then the precision is the total number of digits in the resulting magnitude after rounding. If the conversion is 'a' or 'A' , then the precision must not be specified.

For character, integral, and date/time argument types and the percent and line separator conversions, the precision is not applicable; if a precision is provided, an exception will be thrown.

java.io.PrintWriter

Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError() .

Constructor method

The constructor methods for a PrintWriter can take a File, OutputStream, filename String, and Writer as a parameter.

For File and filename String, additional constructors can take the specified charset. The name of the file or the instance of File to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

For OutputStream and Writer, additional constructors can take a autoFlush flag.

All instance of the PrintWriter objects are without automatic line flushing by default. If the autoFlag is turn on (true) when you create the instance, the println, printf, or format methods will flush the output buffer.

The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

For example:

FileWriter writer = new FileWriter(new File("test"));

PrintWriter pw = PrintWriter(writer)

which creates a PrintWriter object that uses writer whenever it wants to actually write something into a file.

A PrintWriter object will build up the character arrays for you, and it pass them along to the FileWriter that you give it in the constructor.

(Technically, the PrintWriter constructor actually takes a Writer object as a parameter, an abstract class which FileWriter extends. There are other classes that also extend the Writer class, and PrintWriter can be layered on top of any of these.)

Instance methods

The PrintWriter.print method prints various types to the underlying output stream.

Name Description

public void print (boolean)

Prints a boolean value to the underlying output stream.

public void print (char)

Prints a character to the underlying output stream.

public void print (char[])

Prints an array of characters to the underlying output stream.

public void print (double)

Prints a double value to the underlying output stream.

public void print (int)

Prints an integer value to the underlying output stream.

public void print (long)

Prints a long value to the underlying output stream.

public void print (Object)

Prints an object to the underlying output stream.

public void print (float)

Prints a float value to the underlying output stream.

public void print (String)

Prints a String to the underlying output stream.

Additionally, the PrintWriter instance methods have a println() method corresponding to each of the print() methods, which prints the data and then terminates the current line of input.

The PrintWriter.write method writes the next character or characters to the underlying output stream.

Name Description

public void write (char[])

Writes the characters in the provided buffer to the underlying output stream.

public void write (int)

Writes the next character to the underlying output stream.

public void write (String)

Writes the provided String to the underlying output stream.

public void write (char[], int, int)

Writes len characters from the provided buffer, starting at an offset, to the underlying output stream.

public void write (String, int, int)

Writes len characters from the provided string, starting at an offset, to the underlying output stream.

The PrintWriter.printf/format methods

Name Description

public PrintWriter printf(String format, Object... args)

A convenience method to write a formatted string to this writer using the specified format string and arguments. If automatic flushing is enabled, calls to this method will flush the output buffer.

An invocation of this method of the form out.printf(format, args) behaves in exactly the same way as the invocation

     out.format(format, args)

An IllegalFormatException is thrown, if a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions.

public PrintWriter printf(Locale l, String format, Object... args)

A convenience method to write a formatted string to this writer using the specified format string and arguments. If automatic flushing is enabled, calls to this method will flush the output buffer.

An invocation of this method of the form out.printf(l, format, args) behaves in exactly the same way as the invocation

     out.format(l, format, args

An IllegalFormatException is thrown, if a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions.

public PrintWriter format(String format, Object... args)

Writes a formatted string to this writer using the specified format string and arguments. If automatic flushing is enabled, calls to this method will flush the output buffer.

The locale always used is the one returned by Locale.getDefault(), regardless of any previous invocations of other formatting methods on this object.

An IllegalFormatException is thrown if a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions.

public PrintWriter format(Locale l, String format, Object... args)

Writes a formatted string to this writer using the specified format string and arguments. If automatic flushing is enabled, calls to this method will flush the output buffer.

An IllegalFormatException is thrown if a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions.

For example:

public class Sample {
 	public static void main(String[] args) {
        // Create a new instance of a PrintWriter object along with
        // an underlying StringWriter object.
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);

        // Print some random data to the StringWriter.
        Date date = new Date();
        Random rand = new Random(date.getTime());

        for (int i = 0; i < 10; i++)
        {
            printWriter.format("%d%n",rand.nextInt());
        }

        // Flush the buffer.
        printWriter.flush();

        // Display the contents of the StringWriter.
        if (!printWriter.checkError())
        {
            System.out.println(stringWriter.getBuffer());
        }

        // Close the PrintWriter and String Writer objects.
        try {
			stringWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        printWriter.close();
    }
}
Output:
1036089410
1100013281
-294766645
740950771
30727663
186081636
346641328
-50593658
-1349585769
-213545033
 

Notes

Text sent to an output stream may be buffered. To force text through the buffer use PrintWriter.flush(). When you finish your task do not forget to close the resource, use PrintWriter.close() closes the underlying output stream and releases all internal buffers.


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |