Monday 14 November 2016

Working with PrintWriter



 PrintWriteris essentially a character-oriented version of PrintStream.
 It implements the Appendable, Closeable,and Flushable interfaces.
 PrintWriter defines several constructor:
PrintWriter(OutputStreamoutputStream)
PrintWriter(OutputStreamoutputStream, booleanflushOnNewline)
PrintWriter(WriteroutputStream)
PrintWriter(Writer outputStream, booleanflushOnNewline)
Here, outputStream specifies an open OutputStream that will receive output. The flushOnNewline parameter controls whether the output buffer is automatically flushed every time println(), printf(), or format() is called.
        The next set of constructors gives an easy way to construct a PrintWriter that write its output to a file:
PrintWriter(File outputFile) throws FileNotFoundException
PrintWriter(File outputFile, String charSet) throws FileNotFoundException , UnsupportedEncodingException
PrintWriter(String outputFileName) throws FileNotFoundException
PrintWriter(String outputFileName, String charSet) throws FileNotFoundException, UnsupportedEncodingException

These allow a PrintWriter to be created from a File object or by specifying the name of a file.
It is also possible to specify character encoding by passing its name in charSet.
     PrintWritersupports the print() and println() methods for all types, including objects.
     Example:
import java.io.*;
classPrintwriter
{
public static void main(String args[]) throws FileNotFoundException
 {
PrintWriter p=new PrintWriter("File1.txt");
p.println("Hello this is written to the file using print stream");
p.println("Again the next line is also written to the file");
System.out.println("\nData is successfully written to the file");
 }
}
Output:
Data is successfully written to the file

No comments:
Write comments