What are the differences between InputStreamReader and Scanner in Java?

3

I was aware of reading data by Scanner , I know its operation superficially, however I came across some examples using a class called InputStreamReader for reading data.

What are the differences between these approaches and if they are used for the same purpose, which is the best and why.

    
asked by anonymous 03.03.2015 / 01:10

2 answers

6

The class InputStream read data < (eg, FileInputStream to read files, ByteArrayInputStream to read from a byte array, socket.getInputStram() to read from a socket, System.in to read from the console , etc). The Reader class reads 16-bit Unicode characters, including surrogate pairs ).

The function of InputStreamReader is to serve as an adapter ( Adapter ) between the two classes - reads bytes on one side, converts characters from the other , by using a character encoding ( encoding ). That is, it is a Reader that receives InputStream in the build, consuming data from that stream and displaying it as characters for the consumer.

While a Reader is a "lower-level" class (its function is to read characters, not more, not less) o Scanner is a more specialized class, intended to interpret underlying text in several ways (eg a sequence of digits can be a number, true can be a boolean), including using regular expressions. Its function is not to treat streams , including it delegates that responsibility to a specialized class - such as InputStream or Reader .

In the end, you use the most appropriate class (es) for your purpose. You can even use the 3 at the same time:

InputStream is = new FileInputStream("arquivo.txt"); // Lê bytes do arquivo
Reader r = new InputStreamReader(is, "UTF-8"); // Transforma em caracteres
Scanner s = new Scanner(r); // Prepara-se para interpretar esses caracteres de modo semântico
    
03.03.2015 / 04:17
4

In addition to the default buffer size of the first one being much larger than the second, InputStreamReader is designed to read streams > in a general way and with enough control over how to do the reading although do not worry about the content, whereas the Scanner has a more specific function but has better tools to control read content.

Normally, Scanner is used for reading in console, although it can be used to read files, it can be useful in poorly structured files such as XML. This preference is given because it reads data tokens, it understands what is being read - doing a parsing - and this facilitates data entry where there is no guarantee of what can be received. Because it is a class to be used in a more specific and simplified way, it is not thread-safe .

    
03.03.2015 / 01:29