Firstly, the DataOutputStream
in your 2nd example serves no useful purpose1. Indeed, if your Strings contain characters that don't fit into 8 bits, the writeBytes(String)
method is going to mangle the text. Get rid of it. The Data streams are designed for reading and writing fine-grained binary data. For plain bytes, use a plain (or buffered) Input or Output stream.
Secondly, in this specific use-case where you writing the entire output is a single write operation, the BufferedWriter doesn't add any value either.
So in this case. you should be comparing:
File f = new File("source.htm");
Writer w = new FileWriter(f);
w.write("Content");
versus
File f = new File("source.htm");
OutputStream os = new FileOutputStream(f);
os.write("Content".getBytes());
To my mind, the first version looks simpler and cleaner. And it is best to use the Reader
and Writer
stacks for text I/O ... because that's what they were designed for. (They take care of the encoding and decoding issues, cleanly and transparently.)
You could benchmark them if you really need to know which is faster (on your system!) but I suspect there is not a lot of difference ... and that the first version is faster.
1 - I think DataOutputStream has buffering under the covers, but for this use-case, buffering does not help performance.
In use-cases where you are performing multiple (small) writes instead of on big one, there is a significant performance advantage in using a BufferedWriter
(or a BufferedOutputStream
) instead of an unbuffered writer or stream.
The other point is that both versions of your code is using the platform's default character encoding to encode the output file. It may be more appropriate to use a specific encoding independently of the default, or make this a configuration or command line parameter.