PrintStream

PrintStream is a subclass of FilterOutputStream that adds functionality for printing various data values in human-readable text format. It’s commonly used for printing output to the console, files, or any other output stream.

  • Automatically converts primitives and objects to string representation.
  • Methods like print(), println(), and printf() are provided.
  • You can control whether to auto-flush the stream after writing a newline or not.
  • Does not throw IOException for each write, unlike other streams.

Commonly Used Constructors and Methods

Simple Program – Write to Console

Use PrintStream to display different types of data on the console in a formatted manner.

import java.io.*;

public class SimplePrintStreamDemo {
    public static void main(String[] args) {
        PrintStream ps = new PrintStream(System.out);

        ps.println("Welcome to PrintStream Demo!");
        ps.print("The value of PI is: ");
        ps.println(Math.PI);
        ps.printf("Formatted Output: %-10s | %-5d%n", "Mahesh", 90);

        ps.close();
    }
}
/*
Welcome to PrintStream Demo!
The value of PI is: 3.141592653589793
Formatted Output: Mahesh     | 90
*/

Problem Statement:

LotusJavaPrince and Mahesh are developing a banking system. They want to log transaction details to a file using PrintStream. Every time a transaction occurs, the system must write a readable message with user and amount.

import java.io.*;

class TransactionLogger {
    private PrintStream logStream;

    public TransactionLogger(String filename) throws FileNotFoundException {
        logStream = new PrintStream(new FileOutputStream(filename, true));
    }

    public void logTransaction(String user, double amount) {
        logStream.printf("User: %-15s | Amount: ₹%.2f%n", user, amount);
    }

    public void close() {
        logStream.close();
    }
}

public class BankTransactionApp {
    public static void main(String[] args) {
        try {
            TransactionLogger logger = new TransactionLogger("transactions.txt");

            logger.logTransaction("LotusJavaPrince", 1500.50);
            logger.logTransaction("Mahesh", 2200.75);

            logger.close();
            System.out.println("Transactions logged successfully.");
        } catch (FileNotFoundException e) {
            System.err.println("Error opening log file.");
        }
    }
}

Output

User: LotusJavaPrince  | Amount: ₹1500.50
User: Mahesh           | Amount: ₹2200.75Code language: HTTP (http)

PrintStream simplifies printing of all types to streams.

  • Supports formatted output similar to C’s printf.
  • Ideal for logging and user-friendly outputs.
  • Works seamlessly with files, sockets, and console.
Scroll to Top