V
V
Vitaly Vitrenko2015-07-29 21:48:50
Java
Vitaly Vitrenko, 2015-07-29 21:48:50

What is the difference between these input methods?

What's the difference between

Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));

and
Scanner in = new Scanner(new BufferedInputStream(System.in));
?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2015-07-30
@Vestail

Along with the JDK, you can also download the source code for the standard Java libraries. In any IDE, by holding down CTRL and clicking on the name of one or another class, you can go to its source code and wonder what is happening there ...
In your example, we see two constructors, one accepts a character stream (Reader), and the other is a byte stream ("raw" data) (InputStream).
Scanner is designed for convenient reading of text from a stream, i.e. it needs a character stream (Reader). And what does it do with the byte stream? - right, it wraps it in a Reader :) And if we go into the constructor code, we will see this:

public Scanner(InputStream source) {
        this(new InputStreamReader(source), WHITESPACE_PATTERN);
    }

It's simple, depending on the stream available to you (Reader / InputStream), you use the appropriate Scanner constructor. In your example, both options do the same thing.
The java.io library consists of decorators (the pattern is like this), they are like nesting dolls, nesting them one inside the other, you add functionality.
Byte stream, but do you need a character stream? - pffff... wrapped it in an InputStreamReader. Need buffering? - easy, Wrapped in BufferedReader.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question