by Dinesh Thakur Category: Stream

The is another very convenient I/O class that makes writing text to a file as easy as writing text to the console. The PrintWri ter class defines several constructors, the one we would be using is as follows.

Printwriter(OutputStream oStream, boolean autoFlush)

Here, oStreamis an object oftype OutputStream and autoFlush is an boolean variable which if set to true flushes the output stream every time a prin tln () method is invoked.

PrintWriter includes different versions of the print () and prin tln () methods of all types such as int, float etc. including Object. Thus, you can use these methods in the same way as they have been used in System. out. If the argument is not a primitive type, the printWriter methods will call the Object's toString () method and then print out the result.

Now let us consider a program that reads lines of text typed at the keyboard and then writes the same text into a file by appending a line number at the front of each line.


import java.util.Scanner;
public class PrintWriterExample
      public static void main(String[] args) throws FileNotFoundException
         Scanner input = new Scanner(;
         System.out.println("Enter Name of File to Read : ");
         String inputfileName =;
         System.out.print("Enter Name of File in Which Data to be Written : ");
         String outputfileName =;
         FileReader reader = new FileReader(inputfileName);
         Scanner in = new Scanner(reader);
         PrintWriter out = new PrintWriter(outputfileName);
         int lineNumber = 1;
         while (in.hasNext())
              String line = in.nextLine();
              out.print(lineNumber + " : " + line);
             System.out.println("Data Written Successfully");

PrintWrite in Java Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles