gpt4 book ai didi

java - 扫描多个文件并按字母顺序打印

转载 作者:太空宇宙 更新时间:2023-11-04 11:21:04 24 4
gpt4 key购买 nike

我正在使用 Java 读取多个文本文件并打印它们的目录,我想知道为什么输出不按字母顺序排列?

代码片段(也从互联网上获取)

File dir = new File("/home/dilapitan/Desktop/xml-parsing/files/");
File[] listOfFiles = dir.listFiles();
for (File path : listOfFiles) {
System.out.println(path);
}

输出:

dilapitan@NT071855:~/Desktop/xml-parsing$ java Multiple 
/home/dilapitan/Desktop/xml-parsing/files/c.txt
/home/dilapitan/Desktop/xml-parsing/files/b.txt
/home/dilapitan/Desktop/xml-parsing/files/a.txt
dilapitan@NT071855:~/Desktop/xml-parsing$

我可以用输出来做到这一点吗:

a.txt
b.txt
c.txt

提前谢谢您!

最佳答案

引用File#listDir's documentation :

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

如果您想按特定顺序打印它们,则必须自行执行。 Java 8 流为您提供了一种优雅的方式,可以将补丁中的文件名提取结合起来,并在单个语句中对它们进行排序:

Arrays.stream(listOfFiles)
.map(File::getName)
.sorted()
.forEach(System.out::println);

关于java - 扫描多个文件并按字母顺序打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44900492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com