Find files in a folder using Java

前端 未结 12 1914
日久生厌
日久生厌 2020-11-28 08:15

What I need to do if Search a folder say C:\\example

I then need to go through each file and check to see if it matches a few start characters so if fil

相关标签:
12条回答
  • 2020-11-28 08:17

    You give the name of your file, the path of the directory to search, and let it make the job.

    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 讨论(0)
  • 2020-11-28 08:18

    For list out Json files from your given directory.

    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;
            }
        }
    
    0 讨论(0)
  • 2020-11-28 08:19

    Have a look at java.io.File.list() and FilenameFilter.

    0 讨论(0)
  • 2020-11-28 08:20

    To elaborate on this response, Apache IO Utils might save you some time. Consider the following example that will recursively search for a file of a given name:

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

    See:

    • org.apache.commons.io.FileUtils
    • org.apache.commons.io.filefilter.FileFilterUtils
    • https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/filefilter/IOFileFilter.html
    0 讨论(0)
  • 2020-11-28 08:28

    As @Clarke said, you can use java.io.FilenameFilter to filter the file by specific condition.

    As a complementary, I'd like to show how to use java.io.FilenameFilter to search file in current directory and its subdirectory.

    The common methods getTargetFiles and printFiles are used to search files and print them.

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

    I will demo how to use recursive, bfs and dfs to get the job done.

    Recursive:

        /**
     * 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);
    }
    

    Breadth First Search:

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

    Depth First Search:

     /**
     * Search as far as possible along each branch before backtracking
     */
    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();
    }
    
    0 讨论(0)
  • 2020-11-28 08:29
    • Matcher.find and Files.walk methods could be an option to search files in more flexible way
    • String.format combines regular expressions to create search restrictions
    • Files.isRegularFile checks if a path is't directory, symbolic link, etc.

    Usage:

    //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);
    

    Source:

    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 regex for \txt\temp\tempZERO0.txt:

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

    Try endsWith regex for \txt\temp\ZERO0temp.txt:

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

    Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:

    temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
    
    0 讨论(0)
提交回复
热议问题