- It is the most enhanced writer to write character data to the file.
- The main advantage of print writer is we can write any Type of Primitive Type Data Directly to the file.
- bw.write(true)//compile timer error because boolean is not accepted by BufferWriter
- bw.write(100)//will print the letter d, so to print 100 we have to cast it to string
- bw.write(10.5)//compile time error because it does not support double.
- Every time we need to use primitive data type with BufferWriter we need to cast it to String to use it, and casting every type to string will eat up the system memory and reduce the system performance.
- Using BufferReader for new line we have to call a separate method bw.newLine() which adds an extra line of code and in FileWrite adding “\n” every time make the code unreadable now in print writer println method automatically adds the breakline at the end of the line.
- All the above problems are addressed in print and println method of PrintWriter class
Constructors:
PrintWriter pw = new PrintWriter(String fileName);
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.
Methods of PrintWriter :
write(int ch);
write(char[] ch);
write(String s);
flush();
close();
print(char ch);
print(int i);
print(double d);
print(boolean b);
print(String s);
println(char ch);
println(int i);
println(double d);
println(boolean b);
println(String s);
Below program show an example of PrintWriter
package com.fileDemo;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Demo {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter pw = new PrintWriter("/home/tyson/Desktop/temp/file3");
pw.write(100);
pw.print(100);
pw.println(700);
pw.println(true);
pw.println('K');
pw.println("Tyson");
pw.flush();
pw.close();
}
}
Output :
d100700 true K Tyson
What is the difference betwen pw.write(100) and pw.print(100) in the above code ?
- In the case of pw.write(100) the character d will be written into file.
- In case of pw.print(100) the string 100 will be written into the file.