Java: search for a file according to its name in a directory and subdirectories

I need to find the file according to its name in the directory tree. Then specify the path to this file. I found something like this, but this is a search by extension. Can someone help me how can I modify this code for 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();
    }
}
}
+5
source share
5 answers
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();
        }
    }
}
+9
source

Java . java.io.File listFiles(), File ; isDirectory(), File, , .

+2

FileFilter .

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

}

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

, FileUtils, "txt" extenstions "yourfile.whatever"?

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

All Articles