Java Utililty Methods Relative Path Get

List of utility methods to do Relative Path Get

Description

The list of methods to do Relative Path Get are organized into topic(s).

Method

FilerelativeFile(File file, String relativeTo)
relative File
return new File(relativeName(file.getPath(), relativeTo));
StringrelativeFile(Iterable paths, String file)
Given a path to a file and a list of "search paths" returns the relative path of the file (relative to the one search path that matched)
File path = selectPath(paths, file);
File relFile = relativeFile(path, new File(file));
return relFile.getPath();
StringrelativeFileName(final File baseDir, final File file)
relative File Name
final String basePath = baseDir.getAbsolutePath();
final String filePath = file.getAbsolutePath();
if (baseDir.isDirectory() && file.isFile() && filePath.startsWith(basePath)) {
    return filePath.substring(basePath.length() + 1);
} else {
    return filePath.substring(1);
StringrelativeFrom(File from, File to)
relative From
return from.toURI().relativize(to.toURI()).getPath();
StringrelativePath(File baseDir, File child)
relative Path
return baseDir.toPath().relativize(child.toPath()).toString();
StringrelativePath(File baseDir, File storeFile)
relative Path
String prefix = baseDir.getAbsolutePath();
String path = storeFile.getAbsolutePath();
if (!path.startsWith(prefix))
    throw new FileNotFoundException();
path = path.substring(prefix.length());
if (path.startsWith(File.separator))
    return path.substring(1);
return path;
...
StringrelativePath(File baseDir, File storeFile)
Given a directory and a path under it, return filename of the path relative to the directory.
String prefix = baseDir.getCanonicalPath();
String path = storeFile.getCanonicalPath();
if (!path.startsWith(prefix)) {
    throw new FileNotFoundException();
path = path.substring(prefix.length());
if (path.startsWith(File.separator)) {
    return path.substring(1);
...
StringrelativePath(File descendant, File root)
Compute the relative path between two files: root descendant returned /a/b/c /a/b/c/d.txt d.txt /a/b/c /a/b/c/d/e.txt d/e.txt /a/b/c /a/b/d.txt ''
try {
    String rootPath = root.getCanonicalPath().replace('\\', '/');
    String descendantPath = descendant.getCanonicalPath().replace('\\', '/');
    if (descendantPath.startsWith(rootPath))
        return descendantPath.substring(rootPath.length() + 1);
    return "";
} catch (IOException ex) {
    return "";
...
StringrelativePath(File file, String path)
Returns a String with a relative path from the given path
if (file == null || path == null)
    return null;
String absolute = file.getAbsolutePath();
String tmpPath = path.replaceAll("[/\\\\]", Matcher.quoteReplacement(File.separator));
String relative = absolute.substring(absolute.indexOf(tmpPath) + path.length(), absolute.length());
return relative;
StringrelativePath(File from, File to)
relative Path
return relativePath(from, to, File.separatorChar);