I am switching to Java from c++ and now going through some of the documentation on Java IO. So if I want to make buffered character stream from unbuffered byte stream, I can do this in two ways:
Reader input1 = new BufferedReader(new InputStreamReader(new FileInputStream("Xanadu.txt")));
and
Reader input2 = new InputStreamReader(new BufferedInputStream(new FileInputStream("Xanadu.txt")));
So I can make it character and after this buffered or vise versa. What is the difference between them and which is better?
Functionally, there is no difference. The two versions will behave the same way.
There is a likely to be difference in performance, with the first version likely to be a bit faster than the second version when you read characters from the Reader
one at a time.
In the first version, an entire buffer full of data will be converted from bytes to chars in a single operation. Then each read()
call on the Reader
will fetch a character directly from the character buffer.
In the second version, each read()
call on the Reader
performs one or more read()
calls on the input stream and converts only those bytes read to a character.
If I was going to implement this (precise) functionality, I would do it like this:
Reader input = new BufferedReader(new FileReader("Xanadu.txt"));
and let FileReader
deal with the bytes-to-characters decoding under the hood.
There is a case for using an InputStreamReader
, but only if you need to specify the character set for the bytes-to-characters conversion explicitly.