First,we have PrintWriter
java.io.File f=new java.io.File("s.txt");
java.io.PrintWriter out=new java.io.PrintWriter(f);
out.print(5);
out.print(7);
out.close();
Then we have outputstream
java.io.File f=new java.io.File("s.txt");
java.io.FileOutputStream out=new java.io.FileOutputStream(f);
out.write(5);
out.write(7);
out.close();
Whats the difference?
OutputStreamsare meant for binary data. Writers (includingPrintWriter) are meant for text data.You may not see the difference in your specific situation as you’re calling
PrintWriter.write(int)which writes a single character – if the character encoding you’re using just maps characters to the same byte, for characters less than 127, then you’ll see the same result. But if you give it a different encoding, then you’ll see a difference.PrintWriteris also different in that it suppresses IO exceptions – as doesPrintStream, which is the binary stream equivalent ofPrintWriter.