如何按字母顺序File

如何按字母顺序File

本文介绍了如何按字母顺序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()按字母顺序列出文件?

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?

推荐答案

listFiles 方法,有或没有过滤器,不保证任何订单。

The listFiles method, with or without a filter does not guarantee any order.

它但是,会返回一个数组,您可以使用 Arrays.sort()进行排序。

It does, however, return an array, which you can sort with Arrays.sort().

File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
    ...
}

这是有效的,因为文件是一个类似的类,默认情况下按字典顺序对路径名进行排序。如果你想以不同的方式对它们进行排序,你可以定义自己的比较器。

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.

如果你更喜欢使用Streams:

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:

Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)

替换 System.out :: println 包含您想要处理的文件名。如果您只想要以xml结尾的文件名,请执行以下操作:

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:

Files.list(Paths.get(dirName))
    .filter(s -> s.toString().endsWith(".xml"))
    .sorted()
    .forEach(System.out::println)

再次,用您希望的任何处理操作替换打印。

Again, replace the printing with whichever processing operation you would like.

这篇关于如何按字母顺序File.listFiles?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:55