find all.txt上的java正则表达式

find all.txt上的java正则表达式,java,regex,path,Java,Regex,Path,我正在尝试选择已知目录中的所有.txt文件。 例如,我知道路径:C:///Desktop/ 现在,我想获取桌面上的所有.txt文件 那么我应该使用哪个正则表达式,如何搜索它呢?我对java知之甚少。如果你帮助我,我会非常高兴 String regularExpression = ? String path = "C:/../Desktop/"; Pattern pattern = Pattern.compile(regularExpression); boolean isMatched = P

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

那么我应该使用哪个正则表达式,如何搜索它呢?我对java知之甚少。如果你帮助我,我会非常高兴

String regularExpression = ?

String path = "C:/../Desktop/";
Pattern pattern = Pattern.compile(regularExpression);
boolean isMatched = Pattern.matches(regularExpression,path);
答案如下:

String regularExpression = ".*\.txt";
使用:

import java.nio.file.DirectoryStream;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
公共类应用程序{
公共静态void main(字符串[]args)引发异常{
Path dir=Path.get(“/tmp”、“subdir”、“subsubdir”);
try(DirectoryStream=Files.newDirectoryStream(dir,“*.txt”)){
用于(路径:流){
System.out.println(path.getFileName());
}
}    
}
}

在Windows上,按照的说明构建目录的
路径
。此方法接受一个或多个参数,这些参数共同构成一条路径。在我的示例中,参数
/tmp
subdir
subsubdir
导致
/tmp/subdir/subsubdir
。在Windows上,您可能会从诸如
C:
桌面
“path”之类的段构建路径。endsWith(“.txt”)将更快

尝试此操作以处理txt文件,这将同时处理根文件夹和内部文件夹中的所有文件

    public static void main(String[] arg"s) throws Exception {
     File dir = new File("YOUR_ROOT_FILE_PATH");
                    File[] dirs = dir.listFiles();
                    parseFiles(dirs);
}

        public static void parseFiles(File[] files) throws Exception {
                for (File file : files) {
                    if (file.isDirectory()) {
                        parseFiles(file.listFiles());
                    } else {
                        if(file.getAbsolutePath().endsWith(".txt"){
        //do ur stuff here or call a function and pass this file as argument
                        }
                    }
                }

如果您想使用这些文件,请使用包
java.nio
中提供的工具。不要重新发明Oracle已经为您构建的轮子。可能重复的。请解释路径。get()参数:我的路径类似于:C:/Documents and Settings/username/Desktop/那么我应该在路径中写入什么。get()??
    public static void main(String[] arg"s) throws Exception {
     File dir = new File("YOUR_ROOT_FILE_PATH");
                    File[] dirs = dir.listFiles();
                    parseFiles(dirs);
}

        public static void parseFiles(File[] files) throws Exception {
                for (File file : files) {
                    if (file.isDirectory()) {
                        parseFiles(file.listFiles());
                    } else {
                        if(file.getAbsolutePath().endsWith(".txt"){
        //do ur stuff here or call a function and pass this file as argument
                        }
                    }
                }