如何检查给定的路径是否可能是另一条路径的子节点?(How to check if a given path is possible child of another path?)

系统教程 行业动态 更新时间:2024-06-14 16:59:17
如何检查给定的路径是否可能是另一条路径的子节点?(How to check if a given path is possible child of another path?)

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

说c:\Program Files\My Company\test\My App是c:\Program Files的可能孩子。

目前我正在这样做

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

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()); }

最满意答案

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

输出

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

如果你需要更多的可靠性,你可以使用“toRealPath”而不是“toAbsolutePath”。

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".

更多推荐

本文发布于:2023-04-16 14:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/e5b976dfeef6d5c51c6ac504ba8721d9.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   节点   check   path   child

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!