PrintWriter in Java

What is PrintWriter?

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.

How Does PrintWriter Work?

  • Without PrintWriter: When using OutputStream or even FileWriter, you might miss easy-to-use formatting methods like printing formatted text (printf(), println()).
  • With PrintWriter: It provides a higher-level, convenient interface for printing formatted representations of objects, writing text, and handling character data efficiently. It also handles automatic flushing of data when writing to a file or the console.

Constructors of PrintWriter

  • PrintWriter(Writer out)
  • PrintWriter(OutputStream out)
  • PrintWriter(File file)
  • PrintWriter(String fileName)
  • PrintWriter(Writer out, boolean autoFlush)  // Enable auto flushing after println(), printf(), or format() method calls

Key Methods 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.
Code Example

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.

PrintWriter with Console (System.out)

You can also use PrintWriter with System.out to provide more control over writing to the console.

Code Example

Explanation:

  • PrintWriter is used to write text to the console (standard output, System.out).
  • Auto-flushing is enabled, meaning the buffer is automatically flushed after println() and printf() calls.

Differences Between BufferedWriter and PrintWriter

FeatureBufferedWriterPrintWriter
PurposeUsed for efficient character outputUsed for formatted character output
Output DestinationWriter or fileWriter, OutputStream, or file
Formatted OutputDoes not support formatted outputSupports printf(), println(), format()
Auto-flush FeatureNo auto-flush optionSupports auto-flush for certain methods
Use CaseGeneral character-based output to a fileConvenient for formatted output, especially with streams, files, or consoles