Reputation: 35
Why is BufferedReader
created as such
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
while PrintWriter
can be simply constructed like these
PrintWriter pw = new PrintWriter(System.out, true);
BufferedReader
can't be constructed directly from System.in
so it requires InputStreamReader
to convert bytes to char, is this to make it human readable? But PrintWriter
dosen't require a wrap from char back to bytes why is that so, does Java automate it? Because to a machine everything is 1 & 0 anyway.
Upvotes: 0
Views: 195
Reputation: 109547
First:
- Binary data: byte[], InputStream, OutputStream
;
- (Unicode) text: String, char, Reader, Writer
;
- Bridges where binary data has some encoding/Charset and is actually text: InputStreamReader, OutputStreamWriter
(converting from/to given or default Charset).
Now consider:
System.in
is a InputStream
.System.out
and System.err
are a PrintStream
extending from OutputStream
.They are conceived as for binary data, which for Unix is quite normal and useful. For a console however not so useful. However PrintStream
might be a design mishap/error: it has text support, also for passing a Charset; it is a half OutputStreamWriter.
So see
PrintStream
as an old unclean class doing what anOutputStreamWriter + BufferedWriter
does, however not being aWriter
.
BufferedWriter+OutputStreamWriter
has the same complexity (though being reversed) as PrintStream
. One also sees Scanner: new Scanner(System.in)
. This is not a Reader
, and has superfluous support for tokenizing. It like PrintStream
has the advantage of briefness, but is definitely more unclean for its unneeded overhead. (There are quite a lot of bugs mentioned in StackOverflow on Scanner.)
Upvotes: 0
Reputation: 28279
so it requires InputStreamReader to convert bytes to char, is this to make it human readable?
No, it's for performance. Check this to see the difference between them.
And there are BufferedWriter
and BufferedReader
, they have similar functions and constructors.
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new PrintWriter(System.out));
Upvotes: 1