PrintStream

The PrintStream class provides all of the output capabilities. System.out is the standard output and is a PrintStream.

PrintStream implements the Appendable, Closeable, and Flushable interfaces.

PrintStream defines several constructors.

PrintStream(OutputStream outputStream)
outputStream specifies an open OutputStream that will receive output. This constructor does not automatically flush.
PrintStream(OutputStream outputStream, boolean flushOnNewline)
PrintStream(OutputStream outputStream, boolean flushOnNewline, String charSet)
flushOnNewline controls whether to flush buffer every time a newline (\n) character or a byte array is written, or when println( ) is called.

PrintStream(File outputFile) throws FileNotFoundException 
PrintStream(File outputFile, String charSet) throws FileNotFoundException, UnsupportedEncodingException 
PrintStream(String outputFileName) throws FileNotFoundException 
PrintStream(String outputFileName, String charSet) throws FileNotFoundException, UnsupportedEncodingException

construct a PrintStream that writes its output to a file. The file is automatically created. Any preexisting file by the same name is destroyed. You can specify a character encoding by passing its name in charSet.

PrintStream supports the print( ) and println( ) methods for all types, including Object. The PrintStream methods call the object's toString( ) method and then display the result. The printf( ) method uses the Formatter class to format data. It then writes this data to the invoking stream.

The printf( ) method has the following general forms:


PrintStream printf(String fmtString, Object ... args) 
PrintStream printf(Locale loc, String fmtString, Object ... args)

The first version writes args to standard output in the format specified by fmtString, using the default locale.

The second lets you specify a locale.


public class Main {
  public static void main(String args[]) {
    System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);
    System.out.printf("Default floating-point format: %f\n", 1234567.123);
    System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
    System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
    System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);
    System.out.printf("Line up positive and negative values:\n");
    System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
  }
}

PrintStream also defines the format( ) method. It has these general forms:


PrintStream format(String fmtString, Object ... args) 
PrintStream format(Locale loc, String fmtString, Object ... args)

It works exactly like printf( ).

Home 
  Java Book 
    File Stream  

PrintStream:
  1. PrintStream
  2. new PrintStream(File file)
  3. new PrintStream(OutputStream out)