How to list a 2 million files directory in java without having an “out of memory” exception

后端 未结 15 1849
挽巷
挽巷 2020-12-06 00:04

I have to deal with a directory of about 2 million xml\'s to be processed.

I\'ve already solved the processing distributing the work between machines and threads us

15条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 00:34

    If Java 7 is not an option, this hack will work (for UNIX):

    Process process = Runtime.getRuntime().exec(new String[]{"ls", "-f", "/path"});
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    while (null != (line = reader.readLine())) {
        if (line.startsWith("."))
            continue;
        System.out.println(line);
    }
    

    The -f parameter will speed it up (from man ls):

    -f     do not sort, enable -aU, disable -lst
    

提交回复
热议问题