Java PrintWriter Class

Although using System.out to write to the console is acceptable, its use is probably best for the debugging purposes or for sample programs.

For real-world programs, the recommended method of writing to the console when using Java is through the PrintWriter stream.

The PrintWriter is one of the character-based classes. Using a character-based class for the console output makes internationalizing your program easier.

The PrintWriter defines several constructors. The one we will use is shown below :

PrintWriter(OutputStream outputStream, boolean flushingOn)

Here, outputStream is an object of type OutputStream, and flushingOn controls whether Java flushes the output stream every time a println() method (among others) is called. If flushingOn is true, flushing automatically takes place. If false, flushing is not automatic.

The PrintWriter supports the print() and println() methods. Thus, you can use these methods in the same way as you used them with System.out. If an argument is not a simple type, the PrintWriter methods call the object's toString() method and then display the result.

To write to the console by using the PrintWriter, specify System.out for the output stream and automatic flushing. For example, the following line of code creates a PrintWriter that is connected to console output:

PrintWriter pw = new PrintWriter(System.out, true);

Java PrintWriter Example

The following application illustrates using a PrintWriter to handle console output:

/* Java Program Example - Java PrintWriter Class
 * This program demonstrate the PrintWriter */
 
 import java.io.*;
 
 class PrintWriterDemo
 {
     public static void main(String args[])
     {
         
         PrintWriter prnwrt = new PrintWriter(System.out, true);
         
         prnwrt.println("This is a string");
         
         int i = -7;
         prnwrt.println(i);
         double d = 4.5e-7;
         prnwrt.println(d);
         
     }
 }

The output from this Java program is shown below :

java printwriter class

Remember, there is nothing wrong with using System.out simple text output to the console when you are learning Java or debugging your programs. However, using the PrintWriter makes your real-world applications easier to internationalize. Because no advantage gained by using the PrintWriter in the simple programs, we will continue to use System.out to write to the console.

Examples on Files in Java

Here are some examples related to files in Java, you can go for.

Java Online Test


« Previous Tutorial Next Tutorial »