如何检查一个给定的路径是否可能是另一个路径的孩子? [英] How to check if a given path is possible child of another path?

查看:87
本文介绍了如何检查一个给定的路径是否可能是另一个路径的孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到如果给定的路径可能是使用java的另一个路径的孩子。这两个路径可能不存在。



c:\ Program Files \ My Company \test\My App c:\程序文件



的可能子项目前我正在使用

$ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $ my $ .getAbsolutePath());


解决方案

您也可以使用 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));

$ b $ 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,);

$ / code>

输出

<$ p FolderA / FolderB / File = true
/ FolderA / FolderB / F = false
/ FolderA / FolderB = true
/ FolderA / Folder = false
/ FolderA = true
/ Folder = false
/ = true
= false

如果您需要更高的可靠性,您可以使用toRealPath而不是toAbsolutePath。

I am trying to find if given path is possible child of another path using java. Both path may not exist.

Say c:\Program Files\My Company\test\My App is a possible child of c:\Program Files.

Currently I am doing this with

boolean myCheck(File maybeChild, File possibleParent)
{
    return maybeChild.getAbsolutePath().startsWith( possibleParent.getAbsolutePath());
}

解决方案

You can also use java.nio.file.Path to do this much more easily. The java.nio.file.Path.startsWith method seems to handle all possible cases.

Example:

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, "");
}

outputs

/FolderA/FolderB/File = true
/FolderA/FolderB/F = false
/FolderA/FolderB = true
/FolderA/Folder = false
/FolderA = true
/Folder = false
/ = true
 = false

If you need more reliability you can use "toRealPath" instead of "toAbsolutePath".

这篇关于如何检查一个给定的路径是否可能是另一个路径的孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆