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

skaryu picture skaryu · Jun 6, 2011 · Viewed 40.7k times · Source

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

Answer

Udi picture Udi · Jun 6, 2011
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();
        }
    }
}