1

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);
user3553107
  • 211
  • 1
  • 3
  • 6
  • 1
    While buffering might help with large files, I do not see any advantage in using it with keyboard input (`System.in`). And just to prevent future problems, when opening a `Scanner` for `System.in`, either close it at the very end of your code (after everything has been read) or do not close at all. – PM 77-1 Oct 07 '14 at 04:16
  • `System.in` can come from a file too using redirection – kichik Oct 08 '14 at 16:27

2 Answers2

1

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

gerrytan
  • 40,313
  • 9
  • 84
  • 99
1

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.

iColdBeZero
  • 255
  • 2
  • 11