Java Programming Handbook

    Java PrintWriter Class

    In Java, the PrintWriter class is part of the java.io package and provides a convenient way to write formatted text to various output destinations such as files, memory buffers, or even network streams. It supports writing text using methods like print(), println(), and printf(), much like how we use System.out, but it's important not to confuse PrintWriter with PrintStream (used by System.out).

    Unlike FileWriter or BufferedWriter, PrintWriter has the additional capability to handle formatted text and can automatically flush the stream after certain write operations, if configured to do so.

    1. Class Hierarchy#

    java.lang.Object ┛ java.io.Writer └── java.io.PrintWriter

    PrintWriter extends Writer

    2. Constructors#

    PrintWriter(OutputStream out) PrintWriter(OutputStream out, boolean autoFlush) PrintWriter(Writer out) PrintWriter(Writer out, boolean autoFlush) PrintWriter(String fileName) PrintWriter(File file)
    • autoFlush: If true, the output buffer is flushed automatically whenever a println, printf, or format method is called.

    3. Key Methods#

    MethodDescription
    print()Writes data without a newline
    println()Writes data followed by a newline
    printf()Writes formatted string (like C)
    flush()Forces any buffered output to be written
    close()Closes the stream

    4. Examples#

    Example 1: Writing to a file#

    import java.io.*; public class PrintWriterFileExample { public static void main(String[] args) { // Try-with-resources ensures automatic closing of PrintWriter try (PrintWriter writer = new PrintWriter("output.txt")) { writer.println("Hello from PrintWriter!"); writer.println(100); // writing integer writer.println(true); // writing boolean } catch (IOException e) { e.printStackTrace(); } } }

    Output (in output.txt):#

    Hello from PrintWriter! 100 true

    Example 2: Formatted output#

    import java.io.*; public class PrintWriterFormatExample { public static void main(String[] args) { // Printing formatted output to console try (PrintWriter writer = new PrintWriter(System.out)) { writer.printf("%-10s %10.2f\\n", "Price:", 25.50); writer.printf("%-10s %10.2f\\n", "Discount:", 5.75); } } }

    Output:#

    Price: 25.50 Discount: 5.75

    Example 3: Using autoFlush#

    import java.io.*; public class PrintWriterAutoFlushExample { public static void main(String[] args) { // Enabling autoFlush so flush is called after println try (PrintWriter writer = new PrintWriter(System.out, true)) { writer.println("This will flush automatically."); writer.print("This won't add newline but will flush."); } } }

    5. Why Use PrintWriter?#

    • Provides an easier and more readable API for writing text.
    • Allows formatted output similar to System.out.printf().
    • Handles various data types automatically.
    • Optional autoFlush for more control.
    • Can write to files, memory buffers, sockets, etc.

    6. Notes on flush() and close()#

    • flush() is used to push any buffered data to the destination.
    • close() releases system resources and also flushes the stream.
    • If autoFlush is enabled, you may not need to call flush() manually after println() or printf().

    7. Difference Between PrintWriter and PrintStream#

    While both PrintWriter and PrintStream are used for writing output and support methods like print() and println(), they are not the same. Here's a detailed comparison:

    FeaturePrintWriterPrintStream
    Packagejava.iojava.io
    InheritanceExtends Writer (character stream)Extends OutputStream (byte stream)
    Main UseWriting text (characters)Writing raw bytes and text
    Encoding SupportYes, supports character encoding (like UTF-8)Limited encoding support
    Exception HandlingDoes not throw IOException on writing methods (must call checkError() to detect issues)Same behavior (silently handles exceptions unless checked)
    OutputWorks with characters (e.g., writing to a file, console with text)More suitable for binary data or console output
    ExamplePrintWriter pw = new PrintWriter("file.txt");PrintStream ps = new PrintStream("file.txt");
    Common UsageWriting logs, reports, or formatted text to files or consoleSystem output like System.out and binary logs

    Important Note:#

    • System.out is a PrintStream, not a PrintWriter.
    • If you want to write human-readable formatted text with better encoding handling (like UTF-8), use PrintWriter.
    • If you're dealing with console output or binary output, PrintStream is more appropriate.

    Conclusion#

    PrintWriter is a high-level, convenient Writer for printing formatted representations of objects to a text-output stream. Its similarity to System.out makes it intuitive and powerful for writing both simple and formatted data, especially in file and console output scenarios.

    Last updated on Apr 09, 2025