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

前端 未结 5 1001
庸人自扰
庸人自扰 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:50

    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.

    0 讨论(0)
  • 2021-02-03 13:57

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

    0 讨论(0)
  • 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();
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-03 14:05

    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");
        }
    
    0 讨论(0)
  • 2021-02-03 14:17
    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 讨论(0)
提交回复
热议问题