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.
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 :
- FileWriter throws IOException in case of any IO failure.
- None of the PrintWriter methods throws IOException, instead they set a boolean flag which can be obtained using checkError().
- PrintWriter comes with an option of autoflush while creation(default is without autoflush) which will flush after every byte of data is written. In case of FileWriter, caller has to take care of invoking flush.
PrintWriter
gives you some handy methods for formatting like println
and printf
. So if you need to write printed text - you can use it. FileWriter
is more like "low-level" writer that gives you ability to write only strings and char arrays. Basically I don't think there is a big difference what you choose.
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.
While FileWriter has only a basic set of methods, PrintWriter has a rich set of convinience methods, one of them is in your example - PrintWriter.println
.
You should also keep in mind that "methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError()"