简体   繁体   English

DirectoryStream返回路径的顺序如何? 文件名,最后修改,文件大小?

[英]DirectoryStream return path in what kind of order? filename, last modified, filesize?

I am trying to read multiple files in a folder using DirectoryStream. 我正在尝试使用DirectoryStream读取文件夹中的多个文件。 There are 10 items altogether. 共有10个项目。

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 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? DirectoryStream是否按文件名顺序读取文件? 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 ./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());
}

The javadoc of class DirectoryStream explicitly says: DirectoryStream类的javadoc明确表示:

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 Path s. 因此,如果您需要特定的订单,则由您决定Path For example, for an alphabetical sorting you can do like this: 例如,对于字母排序,您可以执行以下操作:

DirectoryStream<Path> stream = ...;
List<Path> list = new ArrayList<>();
stream.forEach(list::add);
list.sort(Comparator.comparing(Path::toString));
for (Path entry: list) {
  System.out.println("reading: " +entry);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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