Home | | Web Programming | The PrintWriter Class - Java

Chapter: Java The Complete Reference : The Java Language : I/O, Applets, and Other Topics

The PrintWriter Class - Java

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

The PrintWriter Class

 

Although using System.out to write to the console is acceptable, its use is probably best for debugging purposes or for sample programs, such as those found in this book. For real-world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class for console output makes internationalizing your program easier.

PrintWriter defines several constructors. The one we will use is shown here: 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.

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 a PrintWriter, specify System.out for the output stream and automatic flushing. For example, this line of code creates a PrintWriter that is connected to console output:

 

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

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

// Demonstrate PrintWriter import java.io.*;

 

public class PrintWriterDemo {

 

public static void main(String args[]) {

 

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

 

pw.println("This is a string"); int i = -7;

 

pw.println(i); double d = 4.5e-7; pw.println(d);

 

}

 

}

 

The output from this program is shown here:

 

This is a string -7

 

4.5E-7

 

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

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Language : I/O, Applets, and Other Topics : The PrintWriter Class - Java |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.