【问题标题】:How to get with numerical order the file names in a folder | JAVA如何按数字顺序获取文件夹中的文件名 | JAVA
【发布时间】:2017-12-25 18:01:37
【问题描述】:

您好,我正在尝试按数字顺序获取文件夹中存在的所有文件。

首先,我检查一个文件夹(主文件夹),其中包含子文件夹。之后,对于每个子文件夹,我将获取其中存在的文件的名称。
我编写了一个代码来为我完成这项工作,但是当我打印(子文件夹的文件名)时,我没有得到正确的顺序。(数字)。

例如,我有一个名为 'test' 的主文件夹,其中存在 3 个名为 Sub1、Sub2、Sub3

的子文件夹
 FOLDER Test *contains* [  FOLDER SUB1   || FOLDER SUB2  ||  FOLDER SUB3 ]

每个子文件夹都有文件名(1.txt, 2.txt,.....,15.txt,16.txt,...,22.txt,...等)

这段代码完成了这项工作......但是......

import java.io.File;
import java.io.FileFilter;
public class Main {
public static void main(String[] args) {
    File file = new File("C:\\test");
    File[] files = file.listFiles(new FileFilter() {
        public boolean accept(File f) {       
            String name=f.getName(); //read every subfodler name
            System.out.println(name);        
            File folder = new File("C:\\test\\"+name); //for each subfolder
            File[] listOfFiles = folder.listFiles();  
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    System.out.println("File " + listOfFiles[i].getName());
                    //print the names of files that included
                } else if (listOfFiles[i].isDirectory()) {
                    System.out.println("Directory " + listOfFiles[i].getName());      
                }    
            } 
            return f.isDirectory();
        }});   
    }   
}

但输出是这样的......

 Folder1               
 File 1.txt
 File 10.txt
 File 11.txt
 File 12.txt
 File 13.txt
 File 14.txt
 File 2.txt
 File 3.txt
 File 4.txt
 File 5.txt
 File 6.txt
 File 7.txt
 File 8.txt
 File 9.txt
 Folder2
 ............... same order as Folder1 ... etc

我如何使用数字顺序获取文件名,这样我将得到的输出将是这样的:

 Folder1               
 File 1.txt
 File 2.txt
 File 3.txt
 File 4.txt
 File 5.txt
 File 6.txt
 File 7.txt
 File 8.txt
 File 9.txt
 File 10.txt
 File 11.txt
 File 12.txt
 File 13.txt
 File 14.txt

【问题讨论】:

  • 它们已经按升序排列。你想要的是numerical order
  • 如果您正确缩进,更多人会查看您的代码。现在,它很难阅读。此外,您正在滥用 FileFilter;它的工作只是过滤文件,它不应该被用作“每个文件”的快捷方式。

标签: java file


【解决方案1】:

一旦您将文件放在列表或数组中,您就可以使用 Collections.sort() 或 Arrays.sort() 以及像 example 这样的自定义比较器对它们进行排序

【讨论】:

  • 这给出了解决方案的提示,但不是一个完整的答案。此外,不需要 ArrayList;只需使用Arrays.sort
  • 这是一个提示。哎呀,他以为他将文件存储在列表中
【解决方案2】:

java.io.File 是一个过时的类。它在几年前被Pathjava.nio.file package 中的其他类所取代,例如文件和路径。

您不应使用过滤器来执行过滤以外的任何操作。是的,它有效,但您依赖的是副作用而不是预期的功能。

为了比较文件名的数字部分,您需要编写自己的Comparator

Path root = Paths.get("C:\\test");

Pattern numericFileNamePattern = Pattern.compile(".*[^0-9]([0-9]+)\\.[^.]+");

Comparator<Path> byNumber = (p1, p2) -> {

    String name1 = p1.getFileName().toString();
    String name2 = p2.getFileName().toString();

    Matcher matcher = numericFileNamePattern.matcher(name1);
    if (matcher.matches()) {

        String digits1 = matcher.group(1);
        String withoutDigits1 = matcher.replaceFirst("");

        matcher.reset(name2);
        if (matcher.matches()) {

            String digits2 = matcher.group(1);
            String withoutDigits2 = matcher.replaceFirst("");

            if (withoutDigits1.equals(withoutDigits2)) {
                long num1 = Long.parseLong(digits1);
                long num2 = Long.parseLong(digits2);

                return Long.compare(num1, num2);
            }
        }
    }

    return p1.compareTo(p2);
};

try (DirectoryStream<Path> dir = Files.newDirectoryStream(root)) {
    for (Path child : dir) {
        if (Files.isDirectory(child)) {

            try (Stream<Path> listing = Files.list(child)) {
                Path[] files = listing.filter(f -> Files.isRegularFile(f))
                    .sorted(byNumber).toArray(Path[]::new);

                for (Path file : files) {
                    System.out.println(file);
                }
            }

        }
    }
}

【讨论】:

  • docs.oracle.com/javase/9/docs/api/java/io/File.html 并没有过时,只是因为 Path 可以做得更多。它仍然没有被弃用,并且是 JDK 的一部分。
  • @Robert 像 Vector、Hashtable 和 Enumeration,它被太多其他类使用以弃用。 File 类除了与其他 API 互操作之外没有任何价值。
猜你喜欢
  • 2016-04-23
  • 1970-01-01
  • 2016-06-28
  • 2012-08-10
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 2019-05-23
相关资源
最近更新 更多