PrintWriter Example

PrintWriter Example Formatting Data

Organizing or customizing the data, the way user wants, is known as formatting the data. PrintWriter class comes with methods to format the data and write to the output stream (not only DOS prompt) as text. This class also contains the methods of PrintStream like print() and println(). This class cannot read raw bytes as in images and for this PrintStream is only preferable.

Extra code for flushing of data is required (that is done automatically with close() method) in case of all streams except PrintStream and PrintWriter. Other streams requires System.out.flush() to flush the data in the middle of the program. The data is automatically flushed with print(), println() and printf() (introduced with JDK 1.5) methods. Even then, for general usage, the flush() method is also provided in PrintStream and PrintWriter classes. These methods do not throw I/O exceptions.

Following is the class signature

public class PrintWriter extends Writer

The print(), println() and write() methods are overloaded a number of times to accept an integer, float, double etc. as parameter.

Displaying at Command Prompt using PrintWriter Formatting Data
The following program on PrintWriter Example uses print() and println() methods to write to DOS prompt.
public class PWDemo
  public static void main(String args[]) throws IOException
    PrintWriter pwriter = new PrintWriter(System.out);
    pwriter.println(new Double(10.5));


PrintWriter Example
Output screen of PrintWriter Example

System.out is passed as parameter to PrintWriter constructor. Using System.out, the data is written to command prompt. You can refer PrintStream for a similar program.

PrintWriter is used to carry data in sockets and Servlets.

Leave a Comment

Your email address will not be published.