Navigation

Own programs

Snippets

Libraries

Deutsch

getRelativePath()

This method, actually getRelativePath(String targetDir, String sourceDir, boolean url), returns the adress of targetDir relative to sourceDir. It works with directories and URLs. The URL-parameter is for the type of the output, true means URL-style path sepparators (/), false means system dependent path sepparators (Windows: \)
You can include a file name in the path, but you don't have to. If you don't specify an file name, don't forget the sepparator at the end (/).

You can download the test class here: RelativeTester.java

Example:

001: import java.io.File;
002:
003: public final class RelativeTester {
004: 	public static void main(String[] args) {
005: 		String relPath = getRelativePath("C:\\muesli\\", "C:\\Programs\\Java\\", false);
006: 		System.out.println(relPath);
007: 		relPath = getRelativePath("C:\\muesli\\", "C:\\Programs\\Java\\", true);
008: 		System.out.println(relPath);
009:
010: 		System.out.println();
011: 		relPath = getRelativePath("http://mywebhome.com/home.html", "http://mywebhome.com/subpage/test.html", true);
012: 		System.out.println(relPath);
013: 		relPath = getRelativePath("http://mywebhome.com/subpage/test.html", "http://mywebhome.com/home.html", true);
014: 		System.out.println(relPath);
015:
016:		System.out.println();
017: 		relPath = getRelativePath("http://mywebhome.com/home.html", "http://myOTHERwebhome.com/subpage/test.html", true);
018: 		System.out.println(relPath);
019: 	}
020:
021: 	public static String getRelativePath(String targetDir, String sourceDir, boolean url) {
         	//[...]
099: 	}
100: }

Result:

..\..\muesli\
../../muesli/

../home.html
subpage/test.html

Exception in thread "main" java.lang.IllegalArgumentException: Two subsites of different Websites
	at Tester.getRelativePath(Tester.java:31)
	at Tester.main(Tester.java:17)