简体   繁体   中英

Java Read files from big directory

I had a directory containing 1 million text files. I wanted to list all the file names. I tried using File.listFiles() and print the file names to console. But it took extremely long time before starting to print the first file name. Is there any faster way to list those file names?

Since listFiles() loads the result into your memory, there won't be any way to accelerate the process with this method.

But you can use Java's DirectoryStream to preload the content into the memory and load each filename. See this link

Path folder = Paths.get("...");
  try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder)) {
    for (Path entry : stream) {
      // Process the entry
    }
   } catch (IOException ex) {
    // An I/O problem has occurred
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM