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

前端 未结 5 1002
庸人自扰
庸人自扰 2021-02-03 13:50

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 h

5条回答
  •  别那么骄傲
    2021-02-03 13:58

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

提交回复
热议问题