How to check if a given path is possible child of another path?

后端 未结 9 947
不思量自难忘°
不思量自难忘° 2020-12-09 01:53

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

相关标签:
9条回答
  • 2020-12-09 02:18

    Be aware of relative paths! I think that simplest solution is something like this:

    public boolean myCheck(File maybeChild, File possibleParent) {
      if (requestedFile.isAbsolute) {
        return possibleParent.resolve(maybeChild).normalize().toAbsolutePath.startsWith(possibleParent.normalize().toAbsolutePath)
      } else {
        return maybeChild.normalize().toAbsolutePath.startsWith(possibleParent.normalize().toAbsolutePath)
      }
    }
    

    In scala you can have similar approach:

    val baseDir = Paths.get("/home/luvar/tmp")
    val baseDirF = baseDir.toFile
    //val requestedFile = Paths.get("file1")
    val requestedFile = Paths.get("../.viminfo")
    val fileToBeRead = if (requestedFile.isAbsolute) {
      requestedFile
    } else {
      baseDir.resolve(requestedFile)
    }
    fileToBeRead.toAbsolutePath
    baseDir.toAbsolutePath
    fileToBeRead.normalize()
    baseDir.normalize()
    val isSubpath = fileToBeRead.normalize().toAbsolutePath.startsWith(baseDir.normalize().toAbsolutePath)
    
    0 讨论(0)
  • 2020-12-09 02:21

    This will work for your example. It will also return true if the child is a relative path (which is often desirable.)

    boolean myCheck(File maybeChild, File possibleParent)
    {
        URI parentURI = possibleParent.toURI();
        URI childURI = maybeChild.toURI();
        return !parentURI.relativize(childURI).isAbsolute();
    }
    
    0 讨论(0)
  • 2020-12-09 02:22

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

    0 讨论(0)
提交回复
热议问题