Java Utililty Methods URL Relative

List of utility methods to do URL Relative

Description

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

Method

StringgetRelativeNameOrURL(File baseDir, File file)
get Relative Name Or URL
String basePath = baseDir.getAbsolutePath();
String path = file.getAbsolutePath();
if (path.startsWith(basePath)) {
    return baseDir.toURI().relativize(file.toURI()).toString();
} else {
    return file.toURI().toString();
StringgetRelativeURI(File fromFile, File toFile)
Returns relative URI between to files.
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;
...
StringgetRelativeURL(File base, File file)
returns the relative path of file to base.
StringBuffer result = new StringBuffer(getRelativePath(base, file));
for (int i = 0; i < result.length(); i++) {
    if (result.charAt(i) == '\\')
        result.setCharAt(i, '/');
return result.toString();
StringgetRelativeUrl(File basePath, File targetPath)
get Relative Url
String baseAbsPath = basePath.getAbsolutePath();
String targetAbsPath = targetPath.getAbsolutePath();
return getRelativeUrl(baseAbsPath, targetAbsPath);
InputStreamgetRelativeURLAsStream(Class clazz, String fileName)
get the input stream of a file relative to (in the same directory as) the specified .class file
can also be used if the .class file resides inside a .jar file
String filePath = getRelativePackagePath(clazz) + "/" + fileName;
return Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);