Check if file is in (sub)directory

前端 未结 8 944
醉梦人生
醉梦人生 2021-01-04 05:50

I would like to check whether an existing file is in a specific directory or a subdirectory of that.

I have two File objects.

File dir;
File file;
<         


        
相关标签:
8条回答
  • 2021-01-04 06:27
    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-01-04 06:27

    How about comparing the paths?

        boolean areRelated = file.getAbsolutePath().contains(dir.getAbsolutePath());
        System.out.println(areRelated);
    

    or

    boolean areRelated = child.getAbsolutePath().startsWith(parent.getAbsolutePath())
    
    0 讨论(0)
提交回复
热议问题