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

问题描述 投票:42回答:12

如果搜索文件夹说C:\example我需要做什么

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

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

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

java file search for-loop directory
12个回答
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");
    }
});

0
投票

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

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

看到:


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;
}

0
投票
  • Matcher.find和Files.walk方法可以选择以更灵活的方式搜索文件
  • String.format结合了正则表达式来创建搜索限制
  • Files.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开始使用\ txt \ temp \ tempZERO0.txt的正则表达式:

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

Try ends与正确的\ txt \ temp \ ZERO0temp.txt正则表达式:

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

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

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

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");
  }
});

16
投票

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

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

4
投票

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


4
投票

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


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;
        }
    }

3
投票

Apache公共IO各种各样

FilenameUtils.wildcardMatch

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


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();
}

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.