Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to read from System.in in Java?

I am reading bunch of integers separated by space or newlines from the standard in using Scanner(System.in).

Is there any faster way of doing this in Java?

like image 804
pathikrit Avatar asked Aug 13 '11 06:08

pathikrit


People also ask

What is the fastest way to read input in Java?

Using Reader Class It uses inputDataStream to read through the stream of data and uses read() method and nextInt() methods for taking inputs. It is the fastest method in java for input.

What do you use to read from System in in Java?

Read Input by Using System.in in Java Using the System.in in a Java code is easy; pass the class in the Scanner constructor and use the nextLine() method. This method reads and returns a string.

What is faster than Scanner in Java?

BufferReader is faster than Scanner as it only reads a character stream. Scanner has methods like nextInt(), nextShort() etc. BufferReader has methods like parseInt(), parseShort() etc. Scanner has method nextLine() to read a line.

What is System in read () in Java?

in is a static data member in the system class of type input stream class. Input stream class belongs java.io package. read byte[] is available in the input stream class. System indicates the current computer system. in indicates standard input device.


1 Answers

Is there any faster way of doing this in Java?

Yes. Scanner is fairly slow (at least according to my experience).

If you don't need to validate the input, I suggest you just wrap the stream in a BufferedInputStream and use something like String.split / Integer.parseInt.


A small comparison:

Reading 17 megabytes (4233600 numbers) using this code

Scanner scanner = new Scanner(System.in); while (scanner.hasNext())     sum += scanner.nextInt(); 

took on my machine 3.3 seconds. while this snippet

BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = bi.readLine()) != null)     for (String numStr: line.split("\\s"))         sum += Integer.parseInt(numStr); 

took 0.7 seconds.

By messing up the code further (iterating over line with String.indexOf / String.substring) you can get it down to about 0.1 seconds quite easily, but I think I've answered your question and I don't want to turn this into some code golf.

like image 153
aioobe Avatar answered Oct 05 '22 17:10

aioobe