且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用Java从文件中读取大量数据

更新时间:2023-01-18 19:08:46

感谢您的每一个回答,但我已经找到了符合我的条件的方法:

Thanks for every answer but I've already found a method that meets my criteria:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("./path"));
int n = readInt(bis);
int t = readInt(bis);
int array[] = new int[n];
for (int i = 0; i < n; i++) {
    array[i] = readInt(bis);
}

private static int readInt(InputStream in) throws IOException {
    int ret = 0;
    boolean dig = false;

    for (int c = 0; (c = in.read()) != -1; ) {
        if (c >= '0' && c <= '9') {
            dig = true;
            ret = ret * 10 + c - '0';
        } else if (dig) break;
    }

    return ret;
}

读取 100 万个整数只需要大约 300 毫秒

It requires only about 300 ms to read 1 mln of integers!