如何按字母顺序排列File.listFiles?

发布于 2024-12-01 06:49:55 字数 868 浏览 0 评论 0原文

我的代码如下:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

江南月 2024-12-08 06:49:55

listFiles 方法,无论有没有过滤器,都不保证任何顺序。

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

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

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

如果您更喜欢使用 Streams:

以下是更现代的方法。要按字母顺序打印给定目录中所有文件的名称,请执行以下操作:

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

将 System.out::println 替换为您想要对文件名执行的任何操作。如果您只需要以 "xml" 结尾的文件名,只需执行以下操作:

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

再次,将打印替换为您想要的任何处理操作。

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().

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.

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)

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.

秋千易 2024-12-08 06:49:55

在 Java 8 中:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

相反的顺序:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));
哭了丶谁疼 2024-12-08 06:49:55

我认为前面的答案是最好的方法,这里是另一种简单的方法。只是为了打印排序结果。

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));
还不是爱你 2024-12-08 06:49:55

这是我的代码:

        try {
            String folderPath = "../" + filePath.trim() + "/";
            logger.info("Path: " + folderPath);
            File folder = new File(folderPath);
            File[] listOfFiles = folder.listFiles();
            int length = listOfFiles.length;
            logger.info("So luong files: " + length);
            ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();

            if (listOfFiles != null && length > 0) {
                int count = 0;
                for (int i = 0; i < length; i++) {
                    if (listOfFiles[i].isFile()) {
                        lstFile.add(new CdrFileBO(listOfFiles[i]));
                    }
                }
                Collections.sort(lstFile);
                for (CdrFileBO bo : lstFile) {
                    //String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";
                    String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";
                    SEQ_START = SEQ_START + 1;
                    bo.getFile().renameTo(new File(folderPath + newName));
                    logger.info("newName: " + newName);
                    logger.info("Next file: " + getSeq(SEQ_START));
                }

            }
        } catch (Exception ex) {
            logger.error(ex);
            ex.printStackTrace();
        }

This is my code:

        try {
            String folderPath = "../" + filePath.trim() + "/";
            logger.info("Path: " + folderPath);
            File folder = new File(folderPath);
            File[] listOfFiles = folder.listFiles();
            int length = listOfFiles.length;
            logger.info("So luong files: " + length);
            ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();

            if (listOfFiles != null && length > 0) {
                int count = 0;
                for (int i = 0; i < length; i++) {
                    if (listOfFiles[i].isFile()) {
                        lstFile.add(new CdrFileBO(listOfFiles[i]));
                    }
                }
                Collections.sort(lstFile);
                for (CdrFileBO bo : lstFile) {
                    //String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";
                    String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";
                    SEQ_START = SEQ_START + 1;
                    bo.getFile().renameTo(new File(folderPath + newName));
                    logger.info("newName: " + newName);
                    logger.info("Next file: " + getSeq(SEQ_START));
                }

            }
        } catch (Exception ex) {
            logger.error(ex);
            ex.printStackTrace();
        }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文