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

前端 未结 22 2298
小蘑菇
小蘑菇 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 10:50

    Recursion produces a smaller solution. This throws an exception if the result is impossible (e.g. different Windows disk) or impractical (root is only common directory.)

    /**
     * Computes the path for a file relative to a given base, or fails if the only shared 
     * directory is the root and the absolute form is better.
     * 
     * @param base File that is the base for the result
     * @param name File to be "relativized"
     * @return the relative name
     * @throws IOException if files have no common sub-directories, i.e. at best share the
     *                     root prefix "/" or "C:\"
     */
    
    public static String getRelativePath(File base, File name) throws IOException  {
        File parent = base.getParentFile();
    
        if (parent == null) {
            throw new IOException("No common directory");
        }
    
        String bpath = base.getCanonicalPath();
        String fpath = name.getCanonicalPath();
    
        if (fpath.startsWith(bpath)) {
            return fpath.substring(bpath.length() + 1);
        } else {
            return (".." + File.separator + getRelativePath(parent, name));
        }
    }
    

提交回复
热议问题