How to construct a relative path in Java from two absolute paths (or URLs)?

前端 未结 22 2679
小蘑菇
小蘑菇 2020-11-22 10:30

Given two absolute paths, e.g.

/var/data/stuff/xyz.dat
/var/data

How can one create a relative path that uses the second path as its base?

22条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:07

    I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:

    public static String getRelativePath(String fromPath, String toPath) {
    
      // This weirdness is because a separator of '/' messes with String.split()
      String regexCharacter = File.separator;
      if (File.separatorChar == '\\') {
        regexCharacter = "\\\\";
      }
    
      String[] fromSplit = fromPath.split(regexCharacter);
      String[] toSplit = toPath.split(regexCharacter);
    
      // Find the common path
      int common = 0;
      while (fromSplit[common].equals(toSplit[common])) {
        common++;
      }
    
      StringBuffer result = new StringBuffer(".");
    
      // Work your way up the FROM path to common ground
      for (int i = common; i < fromSplit.length; i++) {
        result.append(File.separatorChar).append("..");
      }
    
      // Work your way down the TO path
      for (int i = common; i < toSplit.length; i++) {
        result.append(File.separatorChar).append(toSplit[i]);
      }
    
      return result.toString();
    }
    

提交回复
热议问题