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

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


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.


I created a small InputReader class which works just like Java's Scanner but outperforms it in speed by many magnitudes, in fact, it outperforms the BufferedReader as well. Here is a bar graph which shows the performance of the InputReader class I have created reading different types of data from standard input:

enter image description here

Here are two different ways of finding the sum of all the numbers coming from System.in using the InputReader class:

int sum = 0;InputReader in = new InputReader(System.in);// Approach #1try {    // Read all strings and then parse them to integers (this is much slower than the next method).    String strNum = null;    while( (strNum = in.nextString()) != null )        sum += Integer.parseInt(strNum);} catch (IOException e) { }// Approach #2try {    // Read all the integers in the stream and stop once an IOException is thrown    while( true ) sum += in.nextInt();} catch (IOException e) { }


If you asking from competitive programming point of view, where if the submission is not fast enough, it will be TLE.
Then you can check the following method to retrieve String from System.in.I have taken from one of the best coder in java(competitive sites)

private String ns(){    int b = skip();    StringBuilder sb = new StringBuilder();    while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')        sb.appendCodePoint(b);        b = readByte();    }    return sb.toString();}`