skaryu
skaryu

Reputation: 141

java: search file according to its name in directory and subdirectories

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

Upvotes: 11

Views: 51722

Answers (6)

Ousama
Ousama

Reputation: 2790

Find File in a Directory and Nested Sub-Directories :

import java.io.File;
import java.util.Objects;

public class Solution_LocateUniverseFormula {
    public static void main(String[] args) {
        System.out.println(locateUniverseFormula());
    }

    public static String locateUniverseFormula() {
        File root = new File("C:/tmp/documents/");
        String fileName = "universe-formula";

        File[] files = root.listFiles();

        for (File childFile : files) {
            String filePath = find(childFile, fileName);
            if (!Objects.isNull(filePath)) return filePath;
        }

        return null;
    }

    public static String find(File file, String fileName) {
        if (file.getName().startsWith(fileName)) return file.getAbsolutePath();
        if (file.isDirectory()) {
            for (File childFile : file.listFiles()) {
                String filePath = find(childFile, fileName);
                if (!Objects.isNull(childFile)) return filePath;
            }
        }
        return null;
    }
}

Upvotes: 0

sudmong
sudmong

Reputation: 2036

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

Upvotes: 2

Mar
Mar

Reputation: 391

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

Upvotes: 0

Udi
Udi

Reputation: 1110

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

Upvotes: 13

Udi
Udi

Reputation: 1110

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

Upvotes: 0

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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.

Upvotes: 5

Related Questions