Java Utililty Methods URI to Relative URI

List of utility methods to do URI to Relative URI

Description

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

Method

URIgetRelativeURI(URI uri, URI relativeTo)
get the URI relative to the specified base
URI relUri = relativeTo.relativize(uri);
return relUri;
URLrelativeConfig(URI uri)
relative Config
String pwd = System.getProperty("user.dir");
String path = pwd + "/" + uri; 
URL result = new URL("file:///" + path);
return result;
URIrelativeFileToURI(File file)
Returns a URI for the given file.
if (file.isAbsolute())
    return file.toURI();
else {
    String path = file.getPath();
    if (File.separatorChar != '/')
        path = path.replace(File.separatorChar, '/');
    return URI.create(path);
StringrelativePath(final URI baseURI, final URI pathURI)
Path relative to base.
return baseURI.relativize(pathURI).getPath();
URIrelativeURI(String basePath, String path)
Return the relative URI of the given path with respect to the given base path.
return new File(basePath).toURI().relativize(new File(path).toURI());
URIrelativize(URI base, URI child)
relativize
base = base.normalize();
child = child.normalize();
String[] bParts = base.getPath().split("/");
String[] cParts = child.getPath().split("/");
if (bParts.length > 0 && !base.getPath().endsWith("/")) {
    System.arraycopy(bParts, 0, bParts, 0, bParts.length - 1);
int i = 0;
...
URIrelativize(URI base, URI child)
relativize
base = base.normalize();
child = child.normalize();
String[] bParts = base.getPath().split("\\/");
String[] cParts = child.getPath().split("\\/");
int i = 0;
while (i < bParts.length && i < cParts.length && bParts[i].equals(cParts[i])) {
    i++;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < (bParts.length - i); j++) {
    sb.append("../");
for (int j = i; j < cParts.length; j++) {
    if (j != i) {
        sb.append("/");
    sb.append(cParts[j]);
return URI.create(uriEncode(sb.toString()));
URIrelativize(URI base, URI target)
Enhanced version of URI.relativize, the target can now be in parent folder of base URI.
if (!base.getScheme().equals(target.getScheme())) {
    return target;
StringBuilder rel = new StringBuilder();
String path = base.getPath();
String separator = "/";
StringTokenizer tokenizer = new StringTokenizer(target.getPath(), separator);
String targetPart = "";
...
Stringrelativize(URI basePath, File path)
Create path relative to base path
return (basePath != null) ? basePath.relativize(path.toURI()).getPath() : path.getPath();
Stringrelativize(URI baseUri, File f)
relativize
String path = f.getPath();
if (f.isAbsolute()) {
    path = baseUri.relativize(new File(path).toURI()).getPath();
return path;