PrintWriter is a class used for writing formatted text (characters) to an output stream. It can write to various destinations, including files, console, and network sockets. It can be used in a similar way to BufferedWriter but with additional formatting capabilities.
OutputStream or even FileWriter, you might miss easy-to-use formatting methods like printing formatted text (printf(), println()).Constructors of PrintWriter
print(): Writes text (characters) to the output without adding a newline.println(): Writes text followed by a newline.printf(): Formats and writes text to the output.flush(): Flushes the stream, ensuring all data is written to the destination.close(): Closes the writer and releases system resources.import java.io.PrintWriter;import java.io.IOException;public class PrintWriterExample { public static void main(String[] args) { try (PrintWriter pw = new PrintWriter("output.txt")) { // Create PrintWriter to write to a file pw.println("Hello, PrintWriter!"); // Writing text with newline pw.println("This is another line."); pw.printf("Formatted number: %.2f", 3.14159); // Writing formatted text } catch (IOException e) { e.printStackTrace(); } }}Explanation:
PrintWriter writes to the file output.txt.println() writes text followed by a newline.printf() writes formatted text, in this case, a floating-point number with two decimal places.You can also use PrintWriter with System.out to provide more control over writing to the console.
xxxxxxxxxximport java.io.PrintWriter;public class ConsolePrintWriterExample { public static void main(String[] args) { PrintWriter pw = new PrintWriter(System.out, true); // Auto-flush enabled pw.println("Hello from PrintWriter to the console!"); // Print with a newline pw.printf("Formatted string: %s%n", "Java I/O"); // Print formatted text }}Explanation:
PrintWriter is used to write text to the console (standard output, System.out).println() and printf() calls.| Feature | BufferedWriter | PrintWriter |
|---|---|---|
| Purpose | Used for efficient character output | Used for formatted character output |
| Output Destination | Writer or file | Writer, OutputStream, or file |
| Formatted Output | Does not support formatted output | Supports printf(), println(), format() |
| Auto-flush Feature | No auto-flush option | Supports auto-flush for certain methods |
| Use Case | General character-based output to a file | Convenient for formatted output, especially with streams, files, or consoles |