我试图找到给定的路径可能是使用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 = falseIf you need more reliability you can use "toRealPath" instead of "toAbsolutePath".
更多推荐
发布评论