I'm studying the Java I/O but I have a little bit of confusing, can you help me?
I will do examples only with the character stream, because (I think) the byte stream is the same.
I have studied the I/O hierarchy and I know I can chain two or more classes to improve the funcionality, but I don't understand when (and why) I need to use the PrintWriter class (and the PrintStream also)
I have written this code:
1) In the first block I use only the FileWriter with the write method
2) In the second PrintWriter with write
3) PrintWriter with println
4) PrintWriter+FileWriter with write
5) PrintWriter+FileWriter with println
6) PrintWriter+FileOutputStream with println
I have also tried to write a float (a primitive) in my file, but the results are the same both with println and with write.
Somebody can explain me why I need to add PrintWriter in my chain?
If an OutputStream deals with bytes, what about PrintStream.print(String)? It converts chars to bytes using the default platform encoding. Using the default encoding is generally a bad thing since it can lead to bugs when moving from one platform to another, especially if you are generating the file on one platform and consuming it on another.
The advantage is, well, that you can control the character encoding the characters should be written in so that they won't eventually end up as mojibake.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” (Mosher's Law of Software Engineering)
“If debugging is the process of removing bugs, then programming must be the process of putting them in.” (Edsger Dijkstra)
Interesting. I rarely use anything character based in Java networking since most times I work with bytes. When I have used character based networking I have never considered using PrintWriter since it swallows too many exceptions and therefore requires one to explicitly check for errors.
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.