PrintStream in Java

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.

Constructors

PrintStream in Java

Methods

Screen Shot 2020-04-11 at 10.48.55 PMScreen Shot 2020-04-12 at 11.12.12 AMScreen Shot 2020-04-12 at 11.12.22 AM

package com.java.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Locale;

public class PrintStreamExample {

    public static void main(String[] args) {

        FileOutputStream fileOutputStream = null;
        PrintStream printStream = null;

        try {
            fileOutputStream = new FileOutputStream("/Test/TestFolder/test-file10.txt");
            printStream = new PrintStream(fileOutputStream);
            // Printing String
            printStream.print("Hello Guys");
            printStream.println();
            // Printing Boolean
            printStream.print(true);
            printStream.println();
            // Printing Integer
            printStream.print(10); 
            printStream.println();
            // Printing Float
            printStream.print(1.23 f); 
            printStream.println();
            // Format String using format method
              
            printStream.format(Locale.US, "This is %s Example using format", "PrintWriter");  
            printStream.println();
            // Format String using printf method
              
            printStream.printf(Locale.US, "This is %s Example using printf", "PrintWriter");
            printStream.flush();
            System.out.println("Data written to File");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            // Closing the streams
            if (fileOutputStream != null)
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (printStream != null)
                printStream.close();
        }
    }

}
Data written to File
Screen Shot 2020-04-11 at 10.14.19 PM

Leave a Reply

Your email address will not be published. Required fields are marked *