PrintWriter Class

PrintWriter
  • PrintWriter is the most enhanced Writer to write text data to the file.
  • By using FileWriter and BufferedWriter we can write only character data to the File but by using PrintWriter we can write any type of data to the File.
Constructors
PrintWriter pw = new PrintWriter(String fname)
PrintWriter pw = new PrintWriter(File f);
PrintWriter pw = new PrintWriter(Writer w); 

Note

PrintWriter can communicate either directly to the File or via some Writer object also.

Important methods
1. write(int ch)
2. write(char [] ch)
3. write(String s)
4. print(int i)
   print(double d)
   print(char ch)
   print(Boolean b)
   print(char ch[])
5. void flush()
6. close() 

E.g

package com.ashok.files;

import java.io.FileWriter;
import java.io.PrintWriter;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyFile {
   public static void main(String arg[]) throws Exception {
      FileWriter fw = new FileWriter("ashok.txt");
      PrintWriter out = new PrintWriter(fw);
      out.write(97);
      out.println(100);
      out.println(true);
      out.println('c');
      out.println("Waytoeasylearn");
      out.flush();
      out.close();
   }
}

Output

In ashok.txt file
a100
true
c
Waytoeasylearn
PrintWriter Class


Scroll to top