user3553107
user3553107

Reputation: 211

Declaring scanner to read system.in

Looking at Java tutorials, it seems you have to wrap up multiple layers of objects when declaring a scanner e.g. http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));

has both BufferedReader and FileReader. However, if I'm reading from System.in do I need to / is there any benefit to doing this? Do the two options behave differently?

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

vs

Scanner s = new Scanner(System.in);

Upvotes: 1

Views: 146

Answers (2)

iColdBeZero
iColdBeZero

Reputation: 255

Difference is in the efficiency. If used properly BufferedReader prevents bytes that are read from file to be converted into characters and then returned back. So using BufferedReader is recommended.

Additionally, you can specify buffer size, that is very handy.

Upvotes: 1

gerrytan
gerrytan

Reputation: 41133

The buffering part is definitely different. Please read more about IO buffering here: http://docs.oracle.com/javase/tutorial/essential/io/buffers.html

Upvotes: 1

Related Questions