Как найти файл в директории java

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

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java.io.File.list() method. This method is very useful when we want to find files with a specific extension within a folder.

    First Approach

    1. Create a class MyFilenameFilter which implements the FilenameFilter interface and overrides the accept() method of FilenameFilter interface.
    2. The accept() method takes two arguments of which the first one is the directory name and the second one is the filename.
    3. The accept() method returns true if the filename starts with the specified initials else returns false.
    4. The class FindFile contains the main method which accepts the user input like the desired directory to search and the initials of the file to search.
    5. The directory object of File class is initiated with the director name and the filter object of MyFilenameFilter class is initiated with the initials provided by the user.
    6. The list() method is invoked on the dir object  which returns an array of files that satisfy the condition.
    7. The array is iterated over and the name of the required files are printed to the output screen.

    Code Implementation

    Java

    import java.io.*;

    class MyFilenameFilter implements FilenameFilter {

        String initials;

        public MyFilenameFilter(String initials)

        {

            this.initials = initials;

        }

        public boolean accept(File dir, String name)

        {

            return name.startsWith(initials);

        }

    }

    public class Main {

        public static void main(String[] args)

        {

            File directory = new File("/home/user/");

            MyFilenameFilter filter

                = new MyFilenameFilter("file.cpp");

            String[] flist = directory.list(filter);

            if (flist == null) {

                System.out.println(

                    "Empty directory or directory does not exists.");

            }

            else {

                for (int i = 0; i < flist.length; i++) {

                    System.out.println(flist[i]+" found");

                }

            }

        }

    }

    Output

    file.cpp found
    

    Second Approach

    1. The list() method is called on the dir object of the File class and the list of files in the ‘flist’ array.
    2. Each file in the ‘flist’ array is checked against the required filename.
    3. If a match is found it is printed on the screen.

    This method is a bit different from the previous one as the user needs to specify the exact name of the file in this case. 

    Code Implementation

    Java

    import java.io.File;

    public class Main {

        public static void main(String[] argv) throws Exception

        {

            File directory = new File("/home/user/");

            String[] flist = directory.list();

            int flag = 0;

            if (flist == null) {

                System.out.println("Empty directory.");

            }

            else {

                for (int i = 0; i < flist.length; i++) {

                    String filename = flist[i];

                    if (filename.equalsIgnoreCase("file.cpp")) {

                        System.out.println(filename + " found");

                        flag = 1;

                    }

                }

            }

            if (flag == 0) {

                System.out.println("File Not Found");

            }

        }

    }

    Output

    file.cpp found
    

    Last Updated :
    21 Oct, 2020

    Like Article

    Save Article

    I need a to find file according to its name in directory tree. And then show a path to this file. I found something like this, but it search according extension. Could anybody help me how can I rework this code to my needs…thanks

    public class filesFinder {
    public static void main(String[] args) {
        File root = new File("c:\test");
    
        try {
            String[] extensions = {"txt"};
            boolean recursive = true;
    
    
            Collection files = FileUtils.listFiles(root, extensions, recursive);
    
            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                System.out.println(file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }
    

    asked Jun 6, 2011 at 12:07

    skaryu's user avatar

    1

    public class Test {
        public static void main(String[] args) {
            File root = new File("c:\test");
            String fileName = "a.txt";
            try {
                boolean recursive = true;
    
                Collection files = FileUtils.listFiles(root, null, recursive);
    
                for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                    File file = (File) iterator.next();
                    if (file.getName().equals(fileName))
                        System.out.println(file.getAbsolutePath());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    answered Jun 6, 2011 at 12:20

    Udi's user avatar

    UdiUdi

    1,0501 gold badge12 silver badges25 bronze badges

    4

    Recursive directory search in Java is pretty darn easy. The java.io.File class has a listFiles() method that gives all the File children of a directory; there’s also an isDirectory() method you call on a File to determine whether you should recursively search through a particular child.

    answered Jun 6, 2011 at 12:11

    Ernest Friedman-Hill's user avatar

    1

    You can use FileFilter Like this.

    public class MyFileNameFilter implements FilenameFilter {
    
    @Override
    public boolean accept(File arg0, String arg1) {
        // TODO Auto-generated method stub
        boolean result =false;
        if(arg1.startsWith("KB24"))
            result = true;
        return result;
    }
    

    }

    And call it like this

    File f = new File("C:\WINDOWS");
        String []  files  = null;
        if(f.isDirectory()) {  
            
            files = f.list(new MyFileNameFilter());
        }
        
        for(String s: files) {
            
            System.out.print(s);
            System.out.print("t");
        }
    

    Java 8 Lamda make this easier instead of using FileNameFilter, pass lambda expression

       File[] filteredFiles =  f.listFiles((file, name) ->name.endsWith(extn));
       
    

    answered Jun 6, 2011 at 12:21

    sudmong's user avatar

    sudmongsudmong

    2,02613 silver badges12 bronze badges

    4

    I don’t really know what FileUtils does, but how about changing “txt” in extenstions to “yourfile.whatever”?

    answered Jun 6, 2011 at 12:14

    Udi's user avatar

    UdiUdi

    1,0501 gold badge12 silver badges25 bronze badges

    1

    public static File find(String path, String fName) {
        File f = new File(path);
        if (fName.equalsIgnoreCase(f.getName())) return f;
        if (f.isDirectory()) {
            for (String aChild : f.list()) {
                File ff = find(path + File.separator + aChild, fName);
                if (ff != null) return ff;
            }
        }
        return null;
    }
    

    answered May 13, 2015 at 8:34

    Mar's user avatar

    MarMar

    3911 gold badge3 silver badges3 bronze badges

    This example demonstrate how we can use the FileUtils class listFiles() method to search for a file specified by their extensions. We can also define to find the file recursively deep down into the subdirectories.

    package org.kodejava.commons.io;
    
    import org.apache.commons.io.FileUtils;
    
    import java.io.File;
    import java.util.Collection;
    
    public class SearchFileRecursive {
        public static void main(String[] args) {
            File root = new File("F:/Wayan/Kodejava/kodejava-example");
    
            try {
                String[] extensions = {"xml", "java", "dat"};
    
                // Find files within a root directory and optionally its
                // subdirectories which match an array of extensions. When the
                // extensions are null all files will be returned.
                //
                // This method will return matched file as java.io.File
                Collection<File> files = FileUtils.listFiles(root, extensions, true);
    
                for (File file : files) {
                    System.out.println("File = " + file.getAbsolutePath());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Maven Dependencies

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.11.0</version>
    </dependency>
    

    Maven Central

    • Author
    • Recent Posts

    A programmer, recreational runner, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕ every little bit helps, thank you 🙏

    Views: 11,746

    Build Status



    job4j_finder

    • Об утилите
    • Сборка и запуск
    • Использование
    • Контакты

    Об утилите

    Данная утилита умеет искать файлы в заданном каталоге и подкаталогах.

    Сборка и запуск

    Запуск через терминал

    1.Собрать jar через Maven

    mvn install

    2.Запустить jar файл

    java -jar target/finer.jar

    Запуск через IDE

    Перейти к папке src/main/java и файлу ru.job4j.finder.CriterionFinder

    Использование

    Программа ищет данные в заданном каталоге и подкаталогах. Имя файла может задаваться целиком, по маске, по регулярному
    выражению (необязательно).

    Ключи:

    • -d – директория, в которой начинать поиск.
    • -n – имя файла, маска, либо регулярное выражение.
    • -t – тип поиска: mask искать по маске, name по полному совпадению имени, regex по регулярному выражению.
    • -o – результат записать в файл.

    Контакты

    Становов Семён Сергеевич

    Email: sestanovov@gmail.com

    Telegram: @stanovovss

    Добавить комментарий