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

后端 未结 9 1003
不思量自难忘°
不思量自难忘° 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:07

    Old question but a pre-1.7 solution:

    public boolean startsWith(String possibleRoot, String possibleChildOrSame) {
            String[] possiblePath = new File(possibleRoot).getAbsolutePath().replace('\\', '/').split("/");
            String[] possibleChildOrSamePath = new File(possibleChildOrSame).getAbsolutePath().replace('\\', '/').split("/");
    
            if (possibleChildOrSamePath.length < possiblePath.length) {
                return false;
            }
    
            // not ignoring case
            for (int i = 0; i < possiblePath.length; i++) {
                if (!possiblePath[i].equals(possibleChildOrSamePath[i])) {
                    return false;
                }
            }
            return true;
    }
    

    For completeness the java 1.7+ solution:

    public boolean startsWith(String possibleRoot, String possibleChildOrSame) {
            Path p1 = Paths.get(possibleChildOrSame).toAbsolutePath();
            Path p2 = Paths.get(possibleRoot).toAbsolutePath();
            return p1.startsWith(p2);
    }
    

提交回复
热议问题