Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java PrintWriter: Features, Methods, and Practical Examples

Mastering Java PrintWriter

In this tutorial we explore the Java PrintWriter class, its printing methods, and practical code examples.

The PrintWriter class, part of java.io, is designed for writing character data to text files or other output streams. It extends Writer and offers convenient formatting methods.

Unlike other writers, PrintWriter automatically converts primitive types (int, float, char, etc.) to text before writing. It also never throws an IOException; instead, you can detect errors with checkError().

Auto‑flush is a key feature: if enabled, every call to println() or printf() forces the buffer to flush to the underlying stream.

How PrintWriter Works

PrintWriter writes formatted text to an underlying Writer or OutputStream. Its constructor accepts an autoFlush flag and, optionally, a Charset for encoding.

Creating a PrintWriter

First, import the class:

import java.io.PrintWriter;

1. From an existing Writer

FileWriter file = new FileWriter("output.txt");
PrintWriter out = new PrintWriter(file, true); // autoFlush = true

2. From an OutputStream

FileOutputStream fos = new FileOutputStream("output.txt");
PrintWriter out = new PrintWriter(fos, true);

3. Directly from a file name

PrintWriter out = new PrintWriter("output.txt", true);

4. Specifying character encoding

import java.nio.charset.Charset;
PrintWriter out = new PrintWriter("output.txt", true, Charset.forName("UTF-8"));

Using a Charset ensures your text is written with the desired encoding.

Key Methods

print() and println()

These methods write raw or line‑terminated text:

printf()

The printf family supports Java's Formatter syntax. Example:

out.printf("I am %d years old.", 25);

Other useful methods

MethodDescription
close()Closes the stream and releases resources.
checkError()Returns true if a write error has occurred.
append(CharSequence)Appends the given sequence to the writer.

Practical Example

Below is a complete, runnable program that writes formatted text to output.txt using printf():

import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

public class PrintWriterDemo {
    public static void main(String[] args) {
        try (PrintWriter out = new PrintWriter(new FileWriter("output.txt"), true)) {
            int age = 25;
            out.printf("I am %d years old.\n", age);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Running this program creates output.txt with the line:

I am 25 years old.

Further Reading

For the official specification, see the Java PrintWriter API and the Charset documentation.

Java

  1. Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
  2. Java OutputStream: Core Concepts, Methods, and a Practical FileExample
  3. Java FileOutputStream Class – Comprehensive Guide
  4. Mastering Java ByteArrayOutputStream: Methods, Usage, and Practical Examples
  5. Mastering Java’s ObjectInputStream: A Comprehensive Guide
  6. Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
  7. Java BufferedOutputStream: Efficient Byte Writing Explained
  8. Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
  9. Java Writer Class – Mastering Character Streams
  10. Mastering Java’s OutputStreamWriter: Converting Characters to Bytes with Practical Examples