o7planning

Java PrintStream Tutorial with Examples

  1. PrintStream
  2. PrintStream Constructors
  3. PrintStream Methods
  4. Examples
  5. checkError()
  6. print(..) *
  7. print(Object)
  8. println()
  9. println(..) *
  10. println(Object)
  11. printf(..) *
  12. format(..) *
  13. append(..) *

1. PrintStream

PrintStream is a subclass of FilterOutputStream, which is used to print data into an OutputStream it manages. It is also considered as a tool to add functionality to this OutputStream.
Characteristics of PrintStream:
All PrintStream methods do not throw I/O exceptions. To check if an exception occurs you can call checkError() method.
Optionally, PrintStream is capable of auto-flush, meaning that the flush() method will be called immediately after calling println(..) or when printing a text that includes the '\n' character.
All characters printed by PrintStream are converted to bytes using the given encoding or charset, or the system default if not specified. The PrintWriter class should be used in cases where it is required to write characters instead of bytes.
System.out
System.out is a very common and familiar PrintStream object, which is used to print data to the Console screen. It helps you recall the classic code you wrote when you started learning Java:
System.out.println("Hello World!");
See more:
PrintWriter is a class similar to PrintStream, it is used to print data to an internal Writer or OutputStream that it manages.

2. PrintStream Constructors

Constructors to create a PrintStream object without automatic flush:
public PrintStream(OutputStream out)

public PrintStream(File file) throws FileNotFoundException
public PrintStream(File file, Charset charset) throws IOException
public PrintStream(File file, String csn)
                      throws FileNotFoundException, UnsupportedEncodingException

public PrintStream(String fileName) throws FileNotFoundException  
public PrintStream(String fileName, Charset charset) throws IOException
public PrintStream(String fileName, String csn)
                      throws FileNotFoundException, UnsupportedEncodingException
Constructors to create a PrintStream object with an automatic flush option:
public PrintStream(OutputStream out, boolean autoFlush)
public PrintStream(OutputStream out, boolean autoFlush, Charset charset)
public PrintStream(OutputStream out, boolean autoFlush, String encoding)
                                             throws UnsupportedEncodingException
The constructor creates a PrintStream to write data to an OutputStream:
public PrintStream(OutputStream out)
public PrintStream(OutputStream out, boolean autoFlush)  
public PrintStream(OutputStream out, boolean autoFlush, String encoding)
                                                                    throws UnsupportedEncodingException  
public PrintStream(OutputStream out, boolean autoFlush, Charset charset)
The constructors create a PrintStream to write data to a file:
public PrintStream(File file)
public PrintStream(File file, Charset charset) throws IOException
public PrintStream(File file, String csn)
                            throws FileNotFoundException, UnsupportedEncodingException

public PrintStream(String fileName) throws FileNotFoundException  
public PrintStream(String fileName, Charset charset) throws IOException  
public PrintStream(String fileName, String csn)
                            throws FileNotFoundException, UnsupportedEncodingException

3. PrintStream Methods

PrintStream methods:
public boolean checkError()  
protected void setError()  
protected void clearError()  

public void print(boolean b)  
public void print(char c)  
public void print(int i)  
public void print(long l)  
public void print(float f)  
public void print(double d)
public void print(char[] s)  
public void print(String s)  

public void print(Object obj)  

public void println()  
public void println(boolean x)  
public void println(char x)  
public void println(int x)  
public void println(long x)
public void println(float x)  
public void println(double x)
public void println(char[] x)  
public void println(String x)  

public void println(Object x)  

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

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

public PrintStream append(CharSequence csq)  
public PrintStream append(CharSequence csq, int start, int end)  
public PrintStream append(char c)
Other methods, override the methods of the parent class and do not throw an exception:
public void write(int b)  
public void write(byte[] b)  
public void write(byte[] b, int off, int len)  

public void flush()  
public void close()

4. Examples

Get the stack trace from an Exception.
GetStackTraceEx.java
package org.o7planning.printstream.ex;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class GetStackTraceEx {

    public static void main(String[] args) {
        try {
            int a = 100 / 0; // Exception occur here
        } catch (Exception e) {
            String s = getStackTrace(e);
            System.err.println(s);
        }
    }

    public static String getStackTrace(Throwable t) {
        OutputStream baos = new ByteArrayOutputStream();

        // Create PrintStream via PrintStream(OutputStream) constructor.
        PrintStream pw = new PrintStream(baos);

        // Call method: Throwable.printStackTrace(PrintStream)
        t.printStackTrace(pw);
        pw.close();

        String s = baos.toString();
        return s;
    }
}
Output:
java.lang.ArithmeticException: / by zero
    at org.o7planning.printstream.ex.GetStackTraceEx.main(GetStackTraceEx.java:11)

5. checkError()

The checkError() method returns the error status of this PrintStream. In addition, the flush() method is also called if the PrintStream has not been closed.
public boolean checkError()
Note: All methods of PrintStream do not throw IOException, but once an IOException occurs within the methods, its status is error.
This PrintStream error state is only cleared if clearError() is called, but this is a protected method. You can write a class that extends PrintStream and override this method if you want to use it (See example below).
MyPrintStream.java
package org.o7planning.printstream.ex;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class MyPrintStream extends PrintStream {

    public MyPrintStream(File file) throws FileNotFoundException {
        super(file);
    }
    
    @Override
    public void clearError()  {
        super.clearError();    // Call protected method.
    }
}
Example: Use the checkError() method to check the error status of PrintStream:
PrintStream_checkError_ex1.java
package org.o7planning.printstream.ex;

import java.io.File;

public class PrintStream_checkError_ex1 {

    // Windows: C:/SomeFolder/logFile.txt
    private static final String logFilePath = "/Volumes/Data/test/logFile.txt";

    public static void main(String[] args) throws Exception {
        File logFile = new File(logFilePath);

        MyPrintStream mps = new MyPrintStream(logFile);
        int errorCount = 0;
        while (true) {
            // Write log..
            mps.println("Some Log..");
            Thread.sleep(1000);

            // Check if IOException happened.
            if (mps.checkError()) {
                errorCount++;
                mps.clearError();
                if (errorCount > 10) {
                    sendAlertEmail();
                    break;
                }
            }
        }
        mps.close();
    }

    private static void sendAlertEmail() {
        System.out.println("There is a problem in the Log system.");
    }
}

6. print(..) *

The print(..) method is used to print a primitive value.
public void print(boolean b)  
public void print(char c)  
public void print(int i)  
public void print(long l)  
public void print(float f)  
public void print(double d)
public void print(char[] s)  
public void print(String s)
Example:
PrintStream_print_primitive_ex1.java
// System.out is an instance of PrintStream.
PrintStream ps = System.out;

ps.print(true);
ps.println();
ps.print(new char[] { 'a', 'b', 'c' });
ps.println();
ps.print("Text");
Output:
true
abc
Text

7. print(Object)

Convert an object to a String using the String.valueOf(Object) method, and print the result.
public void print(Object obj) {
   this.write(String.valueOf(obj));
}
Example:
PrintStream_print_object_ex1.java
// System.out is an instance of PrintStream.
PrintStream ps = System.out;

Object obj1 = null;
ps.print(obj1);
ps.println();

Object obj2 = new Socket();
ps.print(obj2);
ps.println();

Object obj3 = Arrays.asList("One", "Two", "Three");
ps.print(obj3);
Output:
null
Socket[unconnected]
[One, Two, Three]

8. println()

Print the newline character. The flush() method is also called if the PrintStream has auto flush mode.
public void println() {
    print('\n');
    if(autoFlush) this.flush();
}

9. println(..) *

The println(..) method is used to print a primitive value and a newline character. The flush() method is also called if the PrintStream has auto flush mode.
public void println(boolean x)  
public void println(char x)  
public void println(int x)  
public void println(long x)
public void println(float x)  
public void println(double x)
public void println(char[] x)  
public void println(String x)
Example:
PrintStream_println_primitive_ex1.java
// System.out is an instance of PrintStream.
PrintStream ps = System.out;

ps.println(true);

ps.println(new char[] { 'a', 'b', 'c' });

ps.println("Text");
Output:
true
abc
Text

10. println(Object)

Convert an object to a String using the String.valueOf(Object) method then print the result and the newline character. The flush() method is also called if the PrintStream has auto flush mode. This method works like calling print(Object) and then println().
public void println(Object x) {
       this.write(String.valueOf(x));
       this.write("\n");
       if(this.autoFlush) this.flush();
}
Example:
PrintStream_println_object_ex1.java
// System.out is an instance of PrintStream.
PrintStream ps = System.out;

Object obj1 = null;
ps.println(obj1);

Object obj2 = new Socket();
ps.println(obj2);

Object obj3 = Arrays.asList("One", "Two", "Three");
ps.println(obj3);
Output:
null
Socket[unconnected]
[One, Two, Three]

11. printf(..) *

A convenience method to write a formatted string to this PrintStream using the specified format string and arguments.
public PrintStream printf(String format, Object... args)  
public PrintStream printf(Locale locale, String format, Object... args)
This method works similarly to the code below:
String result = String.format(format, args);
printStream.print(result);

// Or:
String result = String.format(locale, format, args);
printStream.print(result);
See Also:

12. format(..) *

This method works like the printf(..) method.
public PrintStream format(String format, Object... args)  
public PrintStream format(Locale locale, String format, Object... args)
It works like the code below:
String result = String.format(format, args);
printStream.print(result);

// Or:
String result = String.format(locale, format, args);
printStream.print(result);
See Also:

13. append(..) *

The append(..) methods work like the print(..) methods. The only difference is that it returns this PrintStream, so you can call a next method instead of ending with a semicolon ( ; ).
public PrintStream append(CharSequence csq)  
public PrintStream append(CharSequence csq, int start, int end)  
public PrintStream append(char c)
Example:
PrintStream_append_ex1.java
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);

ps.append("This").append(" is").append(' ').append('a').append(" Text");
ps.flush();

String text = baos.toString();
System.out.println(text);// This is a Text

Java IO Tutorials

Show More