确定目录是否包含文件

时间:2011-08-03 15:30:49

标签: java

我有java.io.File个对象A和B,其中A表示目录,B表示文件。 B可以是绝对路径或低于A的0或更多级别的相对路径。确定B是否包含B的最有效方法是什么?

例如,

A是C:\ Users \ bill \ Desktop \ abc \ xyz123,B是C:\ Users \ bob \ Documents \ inc \ data.inc

A是C:\ Users \ bill \ Desktop \ abc \ xyz123,B是C:\ Users \ bob \ Documents \ x1 \ y1 \ inc \ data.inc

A是C:\ Users \ bill \ Desktop \ abc \ xyz123,B是.. \ .. \ .. \ Documents \ inc \ data.inc

3 个答案:

答案 0 :(得分:13)

你可以通过

检查A是否是B的父亲
A.equals(B.getParentFile())

编辑:如果你想检查B是否是A之下的一个或多个级别,只需继续获取ParentFile,直到它为A或null

File C = B.getParentFile();

while(C != null) {
    if(A.equals(C))
        return true;

    C = C.getParentFile();
}

return false;

答案 1 :(得分:0)

getParentFile(),返回父目录,getCanonicalFile()可以使用。像这样:

File bDir = b.getParentFile();
boolean same = bDir.equals(a) || bDir.getCanonicalFile().equals(a.getCanonicalFile());

路径可能很棘手。如果你很幸运,只需getParent()就可以了。使用getCanonicalFile()应该涵盖更复杂的案例。

答案 2 :(得分:0)

使用FileUtils类:

public static boolean directoryContains(File directory,
                                        File child)
                                 throws IOException

确定父目录是否包含子元素(文件或目录)。