Sunday, 26 January 2014

PrintWriter class in java

how to use printwriter class..

The PrintWriter Class


Although using System.out to write to the console is acceptable, its use is recommended mostly for debugging purposes or for sample programs. Java is through a PrintWriter stream. PrintWriteris one of the character-based classes.Using a character-based class for console output makes it easier to internationalize your program. PrintWriter supports the print( ) and println( ) methods for all types including Object.
Thus, you can use these methods in the same way as they have been used with System.out.If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result.PrintWriter defines several constructors. 

The one we will use is shown here: syntax:


PrintWriter(OutputStream outputStream, boolean flushOnNewline)


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

Example of PrintWriter class

// 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

No comments:

Post a Comment