InputStream Reader InputStream Reader

Both InputStream and Reader can be used to read data (from a file or Socket). The main differences are as follows: InputStream is used to read binary numbers (byte streams), while Reader is used to read text data (Unicode characters). So what’s the difference between binary numbers and text data? Essentially, everything read is bytes, and to convert bytes to text, you need to specify an encoding method. The Reader can encode the byte stream into text. Of course, this conversion involves encoding, which by default encodes the byte stream using the system’s default encoding, or you can specify one explicitly, such as “UTF-8”. Although the concept is simple, Java programmers often make a number of coding mistakes, the most common being not specifying how to code. If the correct encoding mode is not specified when a file is read or data is read from a Socket, garbled characters may be displayed in the read data, resulting in data loss.

FileInputStream and FileReader

FileInputStream and FileReader are similar in that they are both used to read data from a file, but FileInputStream is used to read binary data (a byte stream) from a file, while FileReader is used to read character data from a file. FileReader inherits from InputStreamReader, which uses either the default encoding or the encoding used by InputStreamReader. It is important to note that InputStreamReader caches the character encoding, so any changes to the character encoding after the InputStreamReader object is created will have no effect. Here is an example using Filelnputstream and FileReader:



The execution result of the program is: 7465737420726561642066696 c65 test read the file can be seen from the above code, FilelnputStream way is a byte of data read a byte to read, so read speed is slow, at the same time, The read method is a blocking method that either reads a byte or blocks (waiting for data to be read). This method returns the number of bytes read and -1 when it reaches the end of the file. In the example using FileInputStream, each loop reads one byte and then converts it to a hexadecimal string output. The read method in FileReader I reads one character at a time until it reaches the end of the file, which returns -1.


That’s the difference between FileInputStream and FileReader. See other articles on this blog for more Java technology knowledge. If you need Java learning material videos, please leave a comment. Still school Java full set of detailed learning materials video and Python400 set video and programmer training manual, dry goods are very.