Find files in a folder using Java

前端 未结 12 1941
日久生厌
日久生厌 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: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 map = new HashMap();
    
        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 
    * 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 queue = new LinkedList();
        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 stack = new Stack();
        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();
    }
    

提交回复
热议问题