如何按字母顺序排列File.listFiles?
我的代码如下:
class ListPageXMLFiles implements FileFilter {
@Override
public boolean accept(File pathname) {
DebugLog.i("ListPageXMLFiles", "pathname is " + pathname);
String regex = ".*page_\\d{2}\\.xml";
if(pathname.getAbsolutePath().matches(regex)) {
return true;
}
return false;
}
}
public void loadPageTrees(String xml_dir_path) {
ListPageXMLFiles filter_xml_files = new ListPageXMLFiles();
File XMLDirectory = new File(xml_dir_path);
for(File _xml_file : XMLDirectory.listFiles(filter_xml_files)) {
loadPageTree(_xml_file);
}
}
FileFilter
运行良好,但 listFiles()
似乎按相反的字母顺序列出文件。有没有一些快速的方法告诉 listFile()
按字母顺序列出文件?
I've got code as below:
class ListPageXMLFiles implements FileFilter {
@Override
public boolean accept(File pathname) {
DebugLog.i("ListPageXMLFiles", "pathname is " + pathname);
String regex = ".*page_\\d{2}\\.xml";
if(pathname.getAbsolutePath().matches(regex)) {
return true;
}
return false;
}
}
public void loadPageTrees(String xml_dir_path) {
ListPageXMLFiles filter_xml_files = new ListPageXMLFiles();
File XMLDirectory = new File(xml_dir_path);
for(File _xml_file : XMLDirectory.listFiles(filter_xml_files)) {
loadPageTree(_xml_file);
}
}
The FileFilter
is working nicely, but listFiles()
seems to be listing the files in reverse alphabetical order. Is there some quick way of telling listFile()
to list the files in alphabetical order?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
listFiles
方法,无论有没有过滤器,都不保证任何顺序。但是,它确实返回一个数组,您可以使用 Arrays.sort() 对其进行排序。
这是有效的,因为
File
是一个可比较的类,默认情况下按字典顺序对路径名进行排序。如果您想对它们进行不同的排序,您可以定义自己的比较器。如果您更喜欢使用 Streams:
以下是更现代的方法。要按字母顺序打印给定目录中所有文件的名称,请执行以下操作:
将 System.out::println 替换为您想要对文件名执行的任何操作。如果您只需要以
"xml"
结尾的文件名,只需执行以下操作:再次,将打印替换为您想要的任何处理操作。
The
listFiles
method, with or without a filter does not guarantee any order.It does, however, return an array, which you can sort with
Arrays.sort()
.This works because
File
is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.If you prefer using Streams:
A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:
Replace the
System.out::println
with whatever you want to do with the file names. If you want only filenames that end with"xml"
just do:Again, replace the printing with whichever processing operation you would like.
在 Java 8 中:
相反的顺序:
In Java 8:
Reverse order:
我认为前面的答案是最好的方法,这里是另一种简单的方法。只是为了打印排序结果。
I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.
这是我的代码:
This is my code: