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:
Major Differences :
From the source what PrintWriter does when you pass a File is to open it in a buffered way
if you pass it a FileWriter, it will open it, without buffering
This means that the first example can be slightly more efficient. However I would use the
File
without theFileWriter
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()"
PrintWriter
gives you some handy methods for formatting likeprintln
andprintf
. 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.