使用Java查找文件夹中的文件

时间:2011-01-31 15:18:28

标签: java file search for-loop directory

如果搜索文件夹说C:\example

,我需要做什么

然后我需要浏览每个文件并检查它是否与几个起始字符匹配,以便文件启动

temp****.txt
tempONE.txt
tempTWO.txt

所以如果文件以temp开头并且有一个扩展名.txt我想把那个文件名放到File file = new File("C:/example/temp***.txt);中,这样我就可以在文件中读取,然后循环需要转到下一个文件以检查它是否符合上述要求。

12 个答案:

答案 0 :(得分:66)

你想要的是File.listFiles(FileNameFilter filter)

这将为您提供所需目录中与某个过滤器匹配的文件列表。

代码看起来类似于:

// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("temp") && name.endsWith("txt");
    }
});

答案 1 :(得分:32)

您可以使用FilenameFilter,如下所示:

File dir = new File(directory);

File[] matches = dir.listFiles(new FilenameFilter()
{
  public boolean accept(File dir, String name)
  {
     return name.startsWith("temp") && name.endsWith(".txt");
  }
});

答案 2 :(得分:14)

我知道,这是一个老问题。但仅仅为了完整性,lambda版本。

File dir = new File(directory);
File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));

答案 3 :(得分:4)

查看java.io.File.list()FilenameFilter

答案 4 :(得分:4)

考虑一下Apache Commons IO,它有一个名为FileUtils的类,它有一个listFiles方法,在你的情况下可能非常有用。

答案 5 :(得分:3)

Apache公共IO各种

FilenameUtils.wildcardMatch

请参阅Apache javadoc here。它将通配符与文件名匹配。因此,您可以使用此方法进行比较。

答案 6 :(得分:3)

列出您给定目录中的Json文件。

import java.io.File;
    import java.io.FilenameFilter;

    public class ListOutFilesInDir {
        public static void main(String[] args) throws Exception {

            File[] fileList = getFileList("directory path");

            for(File file : fileList) {
                System.out.println(file.getName());
            }
        }

        private static File[] getFileList(String dirPath) {
            File dir = new File(dirPath);   

            File[] fileList = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".json");
                }
            });
            return fileList;
        }
    }

答案 7 :(得分:3)

正如@Clarke所说,您可以使用java.io.FilenameFilter按特定条件过滤文件。

作为补充,我想展示如何使用java.io.FilenameFilter来搜索当前目录及其子目录中的文件。

常用方法getTargetFiles和printFiles用于搜索文件并打印它们。

public class SearchFiles {

    //It's used in dfs
    private Map<String, Boolean> map = new HashMap<String, Boolean>();

    private File root;

    public SearchFiles(File root){
        this.root = root;
    }

    /**
     * List eligible files on current path
     * @param directory
     *      The directory to be searched
     * @return
     *      Eligible files
     */
    private String[] getTargetFiles(File directory){
        if(directory == null){
            return null;
        }

        String[] files = directory.list(new FilenameFilter(){

            @Override
            public boolean accept(File dir, String name) {
                // TODO Auto-generated method stub
                return name.startsWith("Temp") && name.endsWith(".txt");
            }

        });

        return files;
    }

    /**
     * Print all eligible files
     */
    private void printFiles(String[] targets){
        for(String target: targets){
            System.out.println(target);
        }
    }
}

我将演示如何使用递归 bfs dfs 来完成工作。

<强>递归

    /**
 * How many files in the parent directory and its subdirectory <br>
 * depends on how many files in each subdirectory and their subdirectory
 */
private void recursive(File path){

    printFiles(getTargetFiles(path));
    for(File file: path.listFiles()){
        if(file.isDirectory()){
            recursive(file);
        }
    }
    if(path.isDirectory()){
        printFiles(getTargetFiles(path));
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.recursive(searcher.root);
}

广度优先搜索

/**
 * Search the node's neighbors firstly before moving to the next level neighbors
 */
private void bfs(){
    if(root == null){
        return;
    }

    Queue<File> queue = new LinkedList<File>();
    queue.add(root);

    while(!queue.isEmpty()){
        File node = queue.remove();
        printFiles(getTargetFiles(node));
        File[] childs = node.listFiles(new FileFilter(){

            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                if(pathname.isDirectory())
                    return true;

                return false;
            }

        });

        if(childs != null){
            for(File child: childs){
                queue.add(child);
            }
        }
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.bfs();
}

深度优先搜索

/ **      *在回溯之前,尽可能沿每个分支搜索      * /     private void dfs(){

    if(root == null){
        return;
    }

    Stack<File> stack = new Stack<File>();
    stack.push(root);
    map.put(root.getAbsolutePath(), true);
    while(!stack.isEmpty()){
        File node = stack.peek();
        File child = getUnvisitedChild(node);

        if(child != null){
            stack.push(child);
            printFiles(getTargetFiles(child));
            map.put(child.getAbsolutePath(), true);
        }else{
            stack.pop();
        }

    }
}

/**
 * Get unvisited node of the node
 * 
 */
private File getUnvisitedChild(File node){

    File[] childs = node.listFiles(new FileFilter(){

        @Override
        public boolean accept(File pathname) {
            // TODO Auto-generated method stub
            if(pathname.isDirectory())
                return true;

            return false;
        }

    });

    if(childs == null){
        return null;
    }

    for(File child: childs){

        if(map.containsKey(child.getAbsolutePath()) == false){
            map.put(child.getAbsolutePath(), false);
        }

        if(map.get(child.getAbsolutePath()) == false){
            return child; 
        }
    }

    return null;
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.dfs();
}

答案 8 :(得分:1)

从Java 1.8开始,您可以使用Files.list获取流:

Path findFile(Path targetDir, String fileName) throws IOException {
    return Files.list(targetDir).filter( (p) -> {
        if (Files.isRegularFile(p)) {
            return p.getFileName().toString().equals(fileName);
        } else {
            return false;
        }
    }).findFirst().orElse(null);
}

答案 9 :(得分:0)

要详细介绍this response,Apache IO Utils可以为您节省一些时间。考虑以下示例,该示例将递归搜索给定名称的文件:

    File file = FileUtils.listFiles(new File("the/desired/root/path"), 
                new NameFileFilter("filename.ext"), 
                FileFilterUtils.trueFileFilter()
            ).iterator().next();

请参阅:

答案 10 :(得分:0)

您提供文件名,要搜索的目录的路径,并使其完成工作。

private static String getPath(String drl, String whereIAm) {
    File dir = new File(whereIAm); //StaticMethods.currentPath() + "\\src\\main\\resources\\" + 
    for(File e : dir.listFiles()) {
        if(e.isFile() && e.getName().equals(drl)) {return e.getPath();}
        if(e.isDirectory()) {
            String idiot = getPath(drl, e.getPath());
            if(idiot != null) {return idiot;}
        }
    }
    return null;
}

答案 11 :(得分:0)

  • Matcher。find和Files。walk方法可能是一种以更灵活的方式搜索文件的方法
  • 字符串。format组合正则表达式以创建搜索限制
  • 文件。isRegularFile检查路径是否不是目录,符号链接等。

用法:

//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
                                       stream().forEach(System.out::println);

来源:

public final class PathUtils {

    private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
    private static final String endsWithRegex = "(?=[\\.\\n])";
    private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";

    public static List<Path> searchRegularFilesStartsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
    }

    public static List<Path> searchRegularFilesEndsWith(final Path initialPath, 
                             final String fileName, final String fileExt) throws IOException {
        return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
    }

    public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
        return searchRegularFiles(initialPath, "", "");
    }

    public static List<Path> searchRegularFiles(final Path initialPath,
                             final String fileName, final String fileExt)
            throws IOException {
        final String regex = String.format(containsRegex, fileName, fileExt);
        final Pattern pattern = Pattern.compile(regex);
        try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
            return walk.filter(path -> Files.isRegularFile(path) &&
                                       pattern.matcher(path.toString()).find())
                    .collect(Collectors.toList());
        }
    }

    private PathUtils() {
    }
}

Try startsWith 正则表达式,用于\ txt \ temp \ tempZERO0.txt:

(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try endsWith 正则表达式,用于\ txt \ temp \ ZERO0temp.txt:

temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try 包含用于\ txt \ temp \ tempZERO0tempZERO0temp.txt的正则表达式:

temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))