by Dinesh Thakur

The java.io.PrintWriter 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.io.*;

import java.util.Scanner;
public class PrintWriterExample
{
      public static void main(String[] args) throws FileNotFoundException
      {
         Scanner input = new Scanner(System.in);
         System.out.println("Enter Name of File to Read : ");
         String inputfileName = input.next();
         System.out.print("Enter Name of File in Which Data to be Written : ");
         String outputfileName = input.next();
         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);
              lineNumber++;
         }
             System.out.println("Data Written Successfully");
      }
   }

PrintWrite in Java Example