【问题标题】:How to get a list of files and its copies from a directory that matches a file name如何从与文件名匹配的目录中获取文件列表及其副本
【发布时间】:2021-10-08 03:19:54
【问题描述】:

我有一个包含以下文件列表的目录。

  • 测试
  • 测试(1)
  • 测试(2)
  • test_x.log
  • test_x(1).log

在上面的列表中,test(1) 和 test(2) 是原始测试文件的副本。

我想通过提供文件名来获取文件列表(及其副本)。

例如: -输入:测试 -输出列表应包含: - 测试 --测试(1) --test(2)

该列表不应包含 test_x.log 或其副本。根据列表,我应该找到文件副本的最后一次迭代,并从原始测试文件创建一个新的文件副本,如 test(3)。

下面的代码也给出了 test_x.log。尝试使用包含和一些正则表达式模式。没有成功。

String filePath = "C:\\TestFolder";
String finalFileName = "test";

List<File> files = Files.list(Paths.get(filePath))
        .filter(Files::isRegularFile)
        .filter(path -> path.getFileName().toString().startsWith(finalFileName))
        .sorted()
        .map(Path::toFile)
        .collect(Collectors.toList());

【问题讨论】:

  • 文件名通常有扩展名。出于您的目的,我们是否假设没有扩展?如果是这样,那么path.getFileName().toString().matches('test(?:\(\d+\))?') 应该这样做。请参阅regex101.com/r/PFwLCI/1 并注意.matches() 方法添加了开始和结束行锚点。

标签: java regex list file


【解决方案1】:

使用正则表达式:

"test(?:\\(\\d+\\))?(?:\\.|$)"

上下文和测试平台中的正则表达式:

public static void main(String[] args) throws IOException {
    String filePath = "C:\\TestFolder";
    String finalFileName = "test";

    //Regex for matching:
    // C:\TestFolder\test(1).txt || C:\TestFolder\test(2).txt || C:\TestFolder\test.txt
    // and C:\TestFolder\test(1) || C:\TestFolder\test(2) || C:\TestFolder\test
    // regex : "test(?:\\(\\d+\\))?(?:\\.|$)"
    String regex =  String.format("%s(?:\\(\\d+\\))?(?:\\.|$)", finalFileName);
    Pattern extractFilePattern = Pattern.compile(regex); // Pre-compile before loop

    List<File> extractedFiles = Files.list(Paths.get(filePath))
    .filter(Files::isRegularFile)
    .filter(path -> extractFilePattern.matcher(path.getFileName().toString()).find())
    .map(Path::toFile)
    .sorted()
    .collect(Collectors.toList());

    //Output:
    extractedFiles.forEach(System.out::println);
}

输出:

C:\TestFolder\test(1)
C:\TestFolder\test(2)
C:\TestFolder\test

文件系统中的文件:

C:\TestFolder\test(1)
C:\TestFolder\test(2)
C:\TestFolder\test
C:\TestFolder\test_x(1).log
C:\TestFolder\test_x.log
C:\TestFolder\test_x.log

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多