Are PrintWriter and FileWriter in Java the same and no matter which one to use? So far I have used both because their results are the same. Is there some special cases where it makes sense to prefer one over the other?
public static void main(String[] args) {
File fpw = new File("printwriter.txt");
File fwp = new File("filewriter.txt");
try {
PrintWriter pw = new PrintWriter(fpw);
FileWriter fw = new FileWriter(fwp);
pw.write("printwriter text\r\n");
fw.write("filewriter text\r\n");
pw.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
A
PrintWriter
has a different concept of error handling. You need to callcheckError()
instead of using try/catch blocks.Both of these use a
FileOutputStream
internally:but the main difference is that PrintWriter offers special methods:
PrintWriter
doesn't throwIOException
.You should callcheckError()
method for this purpose.The
java.io.PrintWriter
in Java5+ allowed for a convenience method/constructor that writes to file. From the Javadoc;Creates a new PrintWriter, without automatic line flushing, with the specified file. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will encode characters using the default charset for this instance of the Java virtual machine.
According to coderanch.com, if we combine the answers we get:
FileWriter is the character representation of IO. That means it can be used to write characters. Internally FileWriter would use the default character set of the underlying OS and convert the characters to bytes and write it to the disk.
PrintWriter & FileWriter.
Similarities
Differences
Difference between PrintStream and OutputStream: Similar to above explanation, just replace character with byte.
PrintWriter has following methods :
and constructors are :
while FileWriter having following methods :
and constructors are :
Link: http://www.coderanch.com/t/418148/java-programmer-SCJP/certification/Information-PrintWriter-FileWriter
The fact that java.io.FileWriter relies on the default character encoding of the platform makes it rather useless to me. You should never assume something about the environment where your app will be deployed.