java正则表达式查找所有.txt

Bat*_*dak 0 java regex path

我试图选择已知目录中的所有.txt文件.例如,我知道路径:C:/../ Desktop /现在我想要获取桌面上的所有.txt文件.

那么我应该使用哪个regularExpression以及如何搜索它?关于java,我不太了解knowlegde.如果你帮助我,我会很开心.

String regularExpression = ?

String path = "C:/../Desktop/";
Pattern pattern = Pattern.compile(regularExpression);
boolean isMatched = Pattern.matches(regularExpression,path);
Run Code Online (Sandbox Code Playgroud)

小智 5

用途Files.newDirectoryStream:

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class App {

    public static void main(String[] args) throws Exception {
        Path dir = Paths.get("/tmp", "subdir", "subsubdir");
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.txt")) {
            for (Path path : stream) {
                System.out.println(path.getFileName());
            }
        }    
    }
}
Run Code Online (Sandbox Code Playgroud)

在Windows上,Path按照描述构建目录Paths.get.此方法接受一个或多个参数,这些参数一起构建路径.在我的例子中,参数/tmp,subdir以及subsubdir导致/tmp/subdir/subsubdir.在Windows上,您可能会从像C:和这样的段构建路径Desktop.