try{
File file = new File(\"write.txt\");
FileWriter writer = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(writer);
printWriter.prin
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 :
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.
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()"
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.