Java PrintWriter

w‮‬ww.theitroad.com

PrintWriter is a class in Java that allows you to write formatted text to a character stream. It is a subclass of the Writer class and provides a simple way to write formatted data to a file, console, or any other output stream.

Here's an example of how to use PrintWriter to write formatted text to a file:

try {
    PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
    writer.printf("Name: %s\n", "John Doe");
    writer.printf("Age: %d\n", 25);
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

In this example, we create a new PrintWriter object that writes to a file called "output.txt". We then use the printf() method to write formatted text to the file. The %s and %d in the format string are placeholders for the values "John Doe" and 25, respectively. Finally, we close the PrintWriter using the close() method.

The PrintWriter class provides several methods that can be used to write formatted text:

  1. printf(String format, Object... args): This method writes a formatted string to the output stream using the specified format string and arguments.

  2. format(String format, Object... args): This method is similar to printf() and writes a formatted string to the output stream using the specified format string and arguments.

  3. print(String s): This method writes a string to the output stream.

  4. println(String s): This method writes a string to the output stream, followed by a newline character.

  5. print(Object obj): This method writes an object to the output stream.

  6. println(Object obj): This method writes an object to the output stream, followed by a newline character.

  7. flush(): This method flushes the output stream, causing any buffered data to be written.

  8. close(): This method closes the output stream.

Note that many of these methods can throw an IOException if there is an error while writing to the stream. Therefore, it is important to handle exceptions appropriately when using these methods.