leanhvi
leanhvi

Reputation: 13

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?

Upvotes: 1

Views: 2261

Answers (1)

user5718928
user5718928

Reputation:

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
  }

Upvotes: 2

Related Questions