An InputStream is typically always connected to some data source, like a file, network connection, pipe etc. This is also explained in more detail in the Java IO Overview text. InputStreamReader takes an inputstream and converts the bytes Strem into characters when you are reading it.
DataInputStream is a kind of InputStream to read data directly as primitive data types. BufferedInputStream is a kind of inputStream that reads data from a stream and uses a buffer to optimize speed access to data.
Reader is Character Based, it can be used to read or write characters. FileInputStream is Byte Based, it can be used to read bytes. FileReader is Character Based, it can be used to read characters. FileInputStream is used for reading binary files.
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset . The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
An InputStream
reads raw octet (8 bit) data. In Java, the byte
type is equivalent to the char
type in C. In C, this type can be used to represent character data or binary data. In Java, the char
type shares greater similarities with the C wchar_t
type.
An InputStreamReader
then will transform data from some encoding into UTF-16. If "a你们" is encoded as UTF-8 on disk, it will be the byte sequence 61 E4 BD A0 E4 BB AC
. When you pass the InputStream
to InputStreamReader
with the UTF-8 encoding, it will be read as the char sequence 0061 4F60 4EEC
.
The character encoding API in Java contains the algorithms to perform this transformation. You can find a list of encodings supported by the Oracle JRE here. The ICU project is a good place to start if you want to understand the internals of how this works in practice.
As Alexander Pogrebnyak points out, you should almost always provide the encoding explicitly. byte
-to-char
methods that do not specify an encoding rely on the JRE default, which is dependent on operating systems and user settings.
You have to give reader a hint, by providing a character set that your binary file is written in. E.g
Reader reader =
new InputStreamReader(
new FileInputStream( "/path/to/file" ),
"UTF-8" // most likely that the encoding of the file
)
Without a hint it will use your platform default encoding, which in many cases is not what you want.
This link has a nice explanation of encodings: http://www.joelonsoftware.com/articles/Unicode.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With