Java URL Relative getRelativeURI(File fromFile, File toFile)

Here you can find the source of getRelativeURI(File fromFile, File toFile)

Description

Returns relative URI between to files.

License

Open Source License

Parameter

Parameter Description
fromFile File to compute the URI relative to.
toFile Target file or directory.

Return

Relative URI.

Declaration

public static String getRelativeURI(File fromFile, File toFile) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

public class Main {
    /** Returns relative URI between to files.
    Can be used instead of URI.relativize(), which  does not compute
    relative URI's correctly, if toFile is not a subdirectory of fromFile
    (Sun's Java 1.5.0).//ww  w  .j ava2  s .  c  o  m
    @todo Handle special charcters and file names containing slashes.
    @param fromFile File to compute the URI relative to.
    @param toFile Target file or directory.
    @return Relative URI. */
    public static String getRelativeURI(File fromFile, File toFile) {
        assert !fromFile.exists() || !fromFile.isDirectory();
        fromFile = fromFile.getAbsoluteFile().getParentFile();
        assert fromFile != null;
        ArrayList<String> fromList = splitFile(fromFile);
        ArrayList<String> toList = splitFile(toFile);
        int fromSize = fromList.size();
        int toSize = toList.size();
        int i = 0;
        while (i < fromSize && i < toSize && fromList.get(i).equals(toList.get(i)))
            ++i;
        StringBuilder result = new StringBuilder();
        for (int j = i; j < fromSize; ++j)
            result.append("../");
        for (int j = i; j < toSize; ++j) {
            result.append(toList.get(j));
            if (j < toSize - 1)
                result.append('/');
        }
        return result.toString();
    }

    private static ArrayList<String> splitFile(File file) {
        ArrayList<String> list = new ArrayList<String>();
        file = file.getAbsoluteFile();
        try {
            file = file.getCanonicalFile();
        } catch (IOException e) {
        }
        while (file != null) {
            list.add(0, file.getName());
            file = file.getParentFile();
        }
        return list;
    }
}

Related

  1. getRelativeNameOrURL(File baseDir, File file)
  2. getRelativeURL(File base, File file)
  3. getRelativeUrl(File basePath, File targetPath)
  4. getRelativeURLAsStream(Class clazz, String fileName)