try{
File file = new File("write.txt");
FileWriter writer = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("pqr");
printWriter.println("jkl");
printWriter.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.println("abc");
printWriter.println("xyz");
printWriter.close();
}
I don't understand what is difference bet'n these two way. In which scenario i should use printWriter and fileWriter.
FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better.
FileWriter vs FileOutputStreamFileWriter writes streams of characters while FileOutputStream is meant for writing streams of raw bytes. FileWriter deals with the character of 16 bits while on the other hand, FileOutputStream deals with 8-bit bytes.
PrintStream and PrintWriter have nearly identical methods. The primary difference is that PrintStream writes raw bytes in the machine's native character format, and PrintWriter converts bytes to recognized encoding schemes.
“PrintWriter is a class used to write any form of data e.g. int, float, double, String or Object in the form of text either on the console or in a file in Java.” For example, you may use the PrintWriter object to log data in a file or print it on the console.
From the source what PrintWriter does when you pass a File is to open it in a buffered way
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
if you pass it a FileWriter, it will open it, without buffering
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
This means that the first example can be slightly more efficient. However I would use the File
without the FileWriter
because to me it is simpler.
Although both of these internally uses a FileOutputStream , the main difference is that PrintWriter offers some additional methods for formatting like println and printf.
code snippets:
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
public FileWriter(File file) throws IOException {
super(new FileOutputStream(file));
}
Major Differences :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With