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?
Asked
Active
Viewed 1,570 times
1
-
have you tried using the list() method? it returns just the file names, not the whole files. – mlg Feb 13 '17 at 10:02
-
Yeah, `list()` can help in this case. But if my folder was much bigger, 10 millions for example, it would still be a problem. – leanhvi Feb 14 '17 at 04:19
1 Answers
2
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
}

Community
- 1
- 1
-
First of all, thank you for this helpful information. Now I'm wandering if I can use this `DirectoryStream` in parallel. I mean, is there any way to seek the entry of stream? – leanhvi Feb 14 '17 at 04:12
-
Here's [how to convert](http://stackoverflow.com/questions/23932061/convert-iterable-to-stream-using-java-8-jdk/23936723) a ```DirectoryStream``` into a ```Stream``` in order to accelerate parallelism. – Feb 14 '17 at 14:58