Check if file is in (sub)directory

前端 未结 8 942
醉梦人生
醉梦人生 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

    How about comparing the paths?

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

    or

    boolean areRelated = child.getAbsolutePath().startsWith(parent.getAbsolutePath())
    

提交回复
热议问题