我试图找到给定的路径是否可能使用java的另一个路径的子.两条路径可能都不存在.
说c:\Program Files\My Company\test\My App是一个可能的孩子c:\Program Files.
目前我正在这样做
boolean myCheck(File maybeChild, File possibleParent)
{
return maybeChild.getAbsolutePath().startsWith( possibleParent.getAbsolutePath());
}
Run Code Online (Sandbox Code Playgroud)
Jec*_*kov 58
您还可以使用java.nio.file.Path更轻松地执行此操作.该java.nio.file.Path.startsWith方法似乎是处理所有可能的情况.
例:
private static void isChild(Path child, String parentText) {
Path parent = Paths.get(parentText).toAbsolutePath();
System.out.println(parentText + " = " + child.startsWith(parent));
}
public static void main(String[] args) {
Path child = Paths.get("/FolderA/FolderB/File").toAbsolutePath();
isChild(child, "/FolderA/FolderB/File");
isChild(child, "/FolderA/FolderB/F");
isChild(child, "/FolderA/FolderB");
isChild(child, "/FolderA/Folder");
isChild(child, "/FolderA");
isChild(child, "/Folder");
isChild(child, "/");
isChild(child, "");
}
Run Code Online (Sandbox Code Playgroud)
输出
/FolderA/FolderB/File = true
/FolderA/FolderB/F = false
/FolderA/FolderB = true
/FolderA/Folder = false
/FolderA = true
/Folder = false
/ = true
= false
Run Code Online (Sandbox Code Playgroud)
如果需要更高的可靠性,可以使用"toRealPath"而不是"toAbsolutePath".
biz*_*lop 12
File parent = maybeChild.getParentFile();
while ( parent != null ) {
if ( parent.equals( possibleParent ) )
return true;
parent = parent.getParentFile();
}
return false;
Run Code Online (Sandbox Code Playgroud)
And*_*yle 11
除了路径可能不存在(并且规范化可能不成功)之外,这看起来像一个合理的方法,应该在简单的情况下工作.
您可能希望在循环中查看"可能子项"上的getParentFile(),测试它是否与每一步中的父项匹配.如果父级不是(真实)目录,您还可以将比较短路.
也许类似如下:
boolean myCheck(File maybeChild, File possibleParent) throws IOException
{
final File parent = possibleParent.getCanonicalFile();
if (!parent.exists() || !parent.isDirectory()) {
// this cannot possibly be the parent
return false;
}
File child = maybeChild.getCanonicalFile();
while (child != null) {
if (child.equals(parent)) {
return true;
}
child = child.getParentFile();
}
// No match found, and we've hit the root directory
return false;
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您希望子关系是严格的(即目录不是其自身的子目录),您可以更改第child9行的初始分配,child.getParentFile()以便在子容纳目录上进行第一次检查.
这适用于您的示例.true如果孩子是相对路径(这通常是可取的),它也会返回.
boolean myCheck(File maybeChild, File possibleParent)
{
URI parentURI = possibleParent.toURI();
URI childURI = maybeChild.toURI();
return !parentURI.relativize(childURI).isAbsolute();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20989 次 |
| 最近记录: |