PrintStream

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written. All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes.

API

PrintStream API
Constructors/Methods Description
public PrintStream(OutputStream out), public PrintStream(OutputStream out, boolean autoFlush) out - The output stream to which values and objects will be printed
autoFlush - A boolean; if true, the output buffer will be flushed whenever a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.
void print(boolean b), void print(char c), void print(char[] s), void print(double d), void print(float f), void print(int i), void print(long l), void print(Object obj), void print(String s)
void println(boolean b), void println(char c), void println(char[] s), void println(double d), void println(float f), void println(int i), void println(long l), void println(Object obj), void println(String s),
The meanings are clear.
void close() ,void flush(),void write(int b) , void write(byte[] buf, int off, int len) Same as in FileOutputStream.
boolean checkError(),void setError() Flush the stream and check its error state. The internal error state is set to true when the underlying output stream throws an IOException other than InterruptedIOException.

Example

import java.io.*;

public class PrintStreamTest {
    public static void main(String[] args) {
        PrintStream out = null;
        try {
            out = new PrintStream(new FileOutputStream("temp.txt"));
        } catch (IOException ex) {
            ex.printStackTrace();
            return; // stop the program
        }
        out.println("Name : Amy"); // no IOException
        out.println("Age : 18");
        out.close();
    }
}
The output of the program is
Name : Amy
Age : 18