Check if file is in (sub)directory

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

    This method looks pretty solid:

    /**
     * Checks, whether the child directory is a subdirectory of the base 
     * directory.
     *
     * @param base the base directory.
     * @param child the suspected child directory.
     * @return true, if the child is a subdirectory of the base directory.
     * @throws IOException if an IOError occured during the test.
     */
    public boolean isSubDirectory(File base, File child)
        throws IOException {
        base = base.getCanonicalFile();
        child = child.getCanonicalFile();
    
        File parentFile = child;
        while (parentFile != null) {
            if (base.equals(parentFile)) {
                return true;
            }
            parentFile = parentFile.getParentFile();
        }
        return false;
    }
    

    Source

    It is similar to the solution by dacwe but doesn't use recursion (though that shouldn't make a big difference in this case).

提交回复
热议问题