Java - Search for files in a directory

前端 未结 9 632
予麋鹿
予麋鹿 2020-11-29 05:12

This is supposed to be simple, but I can\'t get it - \"Write a program that searches for a particular file name in a given directory.\" I\'ve found a few examples of a hardc

9条回答
  •  有刺的猬
    2020-11-29 05:21

    This method will recursively search thru each directory starting at the root, until the fileName is found, or all remaining results come back null.

    public static String searchDirForFile(String dir, String fileName) {
        File[] files = new File(dir).listFiles();
        for(File f:files) {
            if(f.isDirectory()) {
                String loc = searchDirForFile(f.getPath(), fileName);
                if(loc != null)
                    return loc;
            }
            if(f.getName().equals(fileName))
                return f.getPath();
        }
        return null;
    }
    

提交回复
热议问题