Readers Writers  «Prev  Next»

Lesson 3 Using PrintWriter
ObjectiveFamiliarize yourself with how to use PrintWriter.

Using Java PrintWriters

There are four constructors in the PrintWriter class.
public PrintWriter(Writer out)

public PrintWriter(Writer out, boolean autoFlush)

public PrintWriter(OutputStream out)

public PrintWriter(OutputStream out,
boolean autoFlush)

The PrintWriter can either send data to an OutputStream or to another writer. If autoFlush is set to true, the PrintWriter is flushed every time the println() method is invoked.

The PrintWriter API has not changed in terms of these four constructors since Java 1.1. These constructors have remained the same in Java 1.1 through Java 22, ensuring backward compatibility.
Historical Context
  • The PrintWriter class was introduced in Java 1.1 (1997) as part of the java.io package.
  • The four constructors you listed have been present since Java 1.1 and continue to exist in modern Java versions (e.g., Java 22).
  • They provide different ways to initialize a PrintWriter object using either a Writer or an OutputStream, with an optional autoFlush behavior.

Current Status in Java 22 In Java SE 22, the PrintWriter class still has these same four constructors, along with additional constructors that were introduced later:
  • Since Java 5, additional constructors accepting file names (String) or File objects were introduced:
          public PrintWriter(String fileName)
          public PrintWriter(String fileName, Charset charset)
          public PrintWriter(File file)
          public PrintWriter(File file, Charset charset)
        

  • Since Java 10, additional support for Charset was introduced in the PrintWriter class to handle encoding.

Conclusion: The four constructors in your question have been present since Java 1.1 and have not changed in Java 22. However, newer constructors were added in later Java versions to enhance file handling and encoding support.

print( ) and println( ) Methods in the PrintWriter Class


PrintWriter println() Methods which are overloaded in the PrinterWriter Class

  • Overloaded Methods: The PrintWriter class indeed has several overloaded methods, including println(). Overloading allows methods with the same name to perform different operations based on the types and/or number of arguments passed to them.
  • Number of Overloads for println(): The println() method in PrintWriter is actually overloaded more than 10 times. Here's a breakdown:
  1. println() - Prints a new line to the output stream.
  2. println(boolean x) - Prints the boolean value x followed by a new line.
  3. println(char x) - Prints the character x followed by a new line.
  4. println(int x) - Prints the integer value x followed by a new line.
  5. println(long x) - Prints the long integer value x followed by a new line.
  6. println(float x) - Prints the floating-point value x followed by a new line.
  7. println(double x) - Prints the double-precision floating-point value x followed by a new line.
  8. println(char[] x) - Prints the character array x followed by a new line.
  9. println(String x) - Prints the string x followed by a new line.
  10. println(Object x) - Prints the string representation of the object x (using String.valueOf(x)) followed by a new line.

Additionally, there are variations for each of these with different types of Appendable, File, OutputStream, etc., for constructors, but for println() itself, there are at least 10 versions directly related to primitive types and common reference types, plus additional ones for handling Throwable and formatting (printf style), though not strictly println overloads.
This flexibility allows developers to easily output different types of data without needing to explicitly convert them to strings or other types before printing, enhancing both readability and efficiency of code dealing with console or file output.
Here are the overloaded versions of the println() method in Java's PrintWriter class,
  1. No argument:
    • println()
  2. Primitive types:
    • println(boolean x)
    • println(char x)
    • println(int x)
    • println(long x)
    • println(float x)
    • println(double x)
  3. Arrays and Strings:
    • println(char[] x)
    • println(String x)
  4. Object reference:
    • println(Object x)

Additionally, although not directly part of the println set, there are other methods in PrintWriter that extend its functionality in ways similar to println for different data types:
  1. printf and format methods for formatted output:
    • printf(String format, Object... args)
    • format(String format, Object... args)
  2. Methods to print without a newline:
    • print(boolean x)
    • print(char x)
    • print(int x)
    • print(long x)
    • print(float x)
    • print(double x)
    • print(char[] x)
    • print(String x)
    • print(Object obj)
This list shows that there are more than 10 ways to call println() with different argument types, providing extensive flexibility for output operations in Java.
Any Java object, variable, or literal can be printed by passing it to a print() or println() method.
The println() method follows its argument with a platform-dependent line separator such as \r\n and then flushes the output if autoFlush is enabled. The print() method does not. Otherwise these methods are the same.


checkError( ) method

None of the methods of the PrintWriter class throw IOExceptions. If any exceptions are thrown, they are caught inside the class. You can check to see whether any exceptions have been thrown with checkError().
public boolean checkError()
This method returns true if an error has occurred and false if it hasn't. There's no easy way to determine exactly what the error was, though.

Other PrintWriter methods

The PrintWriter class also contains other PrintWriter methods listed below.

Functions of the Java Methods in PrintWriter Class

The following methods belong to the PrintWriter class in Java, which is used for writing formatted text to an output stream.
1. public void flush()
  • Function: This method forces any buffered output to be written immediately to the underlying stream or writer.
  • Use Case: Useful when writing data that should be immediately available, such as log files.
  • Example:
    PrintWriter writer = new PrintWriter(System.out);
    writer.print("Hello, ");
    writer.flush();  // Ensures "Hello, " is written immediately
        

2. public void close()
  • Function:
    • Closes the PrintWriter and releases any system resources associated with it.
  • Behavior:
    • Also calls flush() before closing.
    • Once closed, further writing attempts result in an IOException.
  • Example:
    • PrintWriter writer = new PrintWriter("output.txt");
      writer.println("Data written");
      writer.close();  // Ensures the file is properly closed
              


3. public void write(int c)
  • Function:
    • Writes a single character to the output stream.
  • Behavior:
    • The integer is cast to a character before writing.
  • Example:
    • PrintWriter writer = new PrintWriter(System.out);
      writer.write(65);  // Writes 'A' (ASCII 65)
      writer.flush();
              

4. public void write(char buf[], int offset, int length)
  • Function:
    • Writes a subset of a character array to the output.
  • Parameters:
    • buf[]: The character array.
    • offset: The starting position in the array.
    • length: The number of characters to write.
  • Example:
    • PrintWriter writer = new PrintWriter(System.out);
      char[] data = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
      writer.write(data, 6, 5);  // Writes "World"
      writer.flush();
              

5. public void write(char buf[])
  • Function:
    Writes an entire character array to the output.
  • Example:
        PrintWriter writer = new PrintWriter(System.out);
        char[] data = {'H', 'e', 'l', 'l', 'o'};
        writer.write(data);  // Writes "Hello"
        writer.flush();
        

6. public void write(String s, int offset, int length)
  • Function:
    • Writes a substring of a string to the output.
  • Parameters:
    • s: The string.
    • offset: The starting position in the string.
    • length: The number of characters to write.
  • Example:

    • PrintWriter writer = new PrintWriter(System.out);
      writer.write("Hello World", 6, 5);  // Writes "World"
      writer.flush();
      

7. public void write(String s)
  • Function: Writes an entire string to the output.
  • Example:
    PrintWriter writer = new PrintWriter(System.out);
    writer.write("Hello World");  // Writes "Hello World"
    writer.flush();
    

Summary Table:
Method Function
flush() Forces buffered output to be written immediately.
close() Closes the stream, flushing any remaining output.
write(int c) Writes a single character.
write(char buf[], int offset, int length) Writes a specific portion of a character array.
write(char buf[]) Writes an entire character array.
write(String s, int offset, int length) Writes a specific substring.
write(String s) Writes an entire string.

Each of these methods plays a crucial role in writing data efficiently to console, files, or network streams in Java!
The usual Writer methods like write() and flush(), though it's rare to use them.
SEMrush Software