I am really confused about the purpose of various io classes, for example, If we have BufferedWriter, why we need a PrintWriter?
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while(s=br.readline()!=null) {
PrintWriter fs = new PrintWriter(new FileWriter(file));
fs.println(s);
}
if the BufferedWriter can not help? I just do not understand the difference between these io classes, can someone explain me?
They have nothing to do with each other. In all truth, I rarely use
PrintWriterexcept to convertSystem.outtemporarily. But anyway.BufferedWriter, likeBufferedReader/BufferedInputStream/BufferedOutputStreammerely decorates the enclosedWriterwith a memory buffer (you can specify the size) or accept a default. This is very useful when writing to slow Writers like network or file based. (Stuff is committed in memory and only occasionally to disk for example) By buffering in memory the speed is greatly increased – try writing code that writes to say a 10 mb file with justFileWriterand then compare to the same withBufferedWriterwrapped around it.So that’s
BufferedWriter. It throws in a few convenience methods, but mostly it just provides this memory buffer.PrintWritermostly is a simple decorator that adds some specific write methods for various types likeString,float, etc, so you don’t have to convert everything to raw bytes.Edited:
This already has come up