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

前端 未结 9 2102
梦如初夏
梦如初夏 2020-11-30 19:17

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 Ja

9条回答
  •  日久生厌
    2020-11-30 20:10

    You can read from System.in in a digit by digit way. Look at this answer: https://stackoverflow.com/a/2698772/3307066.

    I copy the code here (barely modified). Basically, it reads integers, separated by anything that is not a digit. (Credits to the original author.)

    private static int readInt() throws IOException {
        int ret = 0;
        boolean dig = false;
        for (int c = 0; (c = System.in.read()) != -1; ) {
            if (c >= '0' && c <= '9') {
                dig = true;
                ret = ret * 10 + c - '0';
            } else if (dig) break;
        }
        return ret;
    }
    

    In my problem, this code was approx. 2 times faster than using StringTokenizer, which was already faster than String.split(" "). (The problem involved reading 1 million integers of up to 1 million each.)

提交回复
热议问题