Java 确定目录是否包含文件

Java 确定目录是否包含文件,java,Java,我有java.io.File对象A和B,其中A表示目录,B表示文件。B可以是绝对路径,也可以是比a低0或更多级别的相对路径。确定B是否包含在a中的最有效方法是什么 比如说, 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:\Us

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

比如说,

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

您可以通过执行以下操作检查A是否是B的父级

A.equals(B.getParentFile())
编辑:如果要检查B是否比A低一级或多级,只需继续获取父文件,直到它为A或null

File C = B.getParentFile();

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

    C = C.getParentFile();
}

return false;
,它返回父目录,可以使用。像这样:

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

路径可能很棘手。如果幸运的话,只需要
getParent()
。使用
getCanonicalFile()
应该涵盖更复杂的情况。

使用FileUtils类:

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

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

来吧,伙计……它就在
文件
API-中。请将此站点视为卡住时的去处,在你开始之前没有。也许我过度简化了这个例子。你想检查B是在A的正下方还是在A下的任何文件夹中吗?无论哪种方式,您都应该能够使用getParentFile()和循环来获得结果