4

I am trying to read multiple files in a folder using DirectoryStream. There are 10 items altogether.

doc_01.txt, doc_02.txt, doc_03.txt, doc_04.txt, doc_05.txt, doc_06.txt, doc_07.txt, doc_08.txt, doc_09.txt, doc_10.txt

I wanted the file to be read in the order of their filename. Does DirectoryStream read the file in order of their filename? Because this is the result I get:

./mydata/doc_01.txt, ./mydata/doc_02.txt, ./mydata/doc_03.txt, ./mydata/doc_04.txt, ./mydata/doc_08.txt, ./mydata/doc_07.txt, ./mydata/doc_09.txt, ./mydata/doc_10.txt, ./mydata/doc_05.txt, ./mydata/doc_06.txt

This is my code:

public static void readData(){
    Instant start = Instant.now();
    System.out.println("Start reading");

    Path path = Paths.get(String.join(File.separator, ".", "mydata"));

    try(DirectoryStream<Path> stream = 
            Files.newDirectoryStream(path, "*.txt")
    ){
        for(Path entry : stream){
            System.out.println("reading: " +entry.toString());
        }
    }catch(IOException e){
        System.err.println("Error: " + e.getMessage());
        e.printStackTrace();
    }
    Instant end = Instant.now();
    System.out.println("Done in " + Duration.between(start, end).toString());
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
udon
  • 93
  • 1
  • 5

1 Answers1

9

The javadoc of class DirectoryStream explicitly says:

The elements returned by the iterator are in no specific order. Some file systems maintain special links to the directory itself and the directory's parent directory. Entries representing these links are not returned by the iterator.

So, if you need a specific order, it's up to you to sort the Paths. For example, for an alphabetical sorting you can do like this:

DirectoryStream<Path> directoryStream = ...;
StreamSupport.stream(directoryStream.spliterator(), false)
    .sorted(Comparator.comparing(Path::toString))
    .forEach(p -> { System.out.println("reading: " + p); });
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • I guess i didnt read the API thoroughly. But this explains it then. thanks alot. :) This question can be closed now i supposed. – udon Apr 30 '17 at 14:13
  • 1
    Thanks, solves my problem.. On Windows they are returned in order but on MacOS they are not, as I do my main testing on Windows I have only just picked up on this problem. – Paul Taylor Nov 03 '21 at 10:24