PrintWriter Class

PrintWriter Class

In this tutorial, we are going to discuss about PrintWriter class in Java. The PrintWriter class in Java, found in the java.io package, is used to write formatted text to a destination, such as a file or an output stream. It provides convenient methods for writing various data types and formatting them as text.

PrintWriter Class
  • 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

That’s all about the PrintWriter Class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

PrintWriter Class
Scroll to top