URL Relative
In this chapter you will learn:
Resolve a relative URL
URL class constructor has another good feature. We can use the constructor to remove a relative URL.
import java.net.MalformedURLException;
import java.net.URL;
// j a v a2 s. co m
public class Main{
public static void main(String[] a) {
try {
URL base = new URL("http://www.java2s.com/");
URL relative = new URL(base, "index.html");
System.out.println(relative);
} catch (MalformedURLException ex) {
;
}
}
}
The code above generates the following result.
Parent file and folder
In the following code we create a URL which points
to www.java2s.com/abc/d.htm
. After that we resolve a URL relative
as ../a.htm
. Here the double dots ..
means
go to the parent folder. The current folder is www.java2s.com/abc
parent folder is the www.java2s.com
.
../a.htm
refers to www.java2s.com/a.htm
which is the
output.
import java.net.URL;
//from ja v a2 s .c om
public class Main {
public static void main(String[] argv) throws Exception {
URL relativeURL, baseURL;
baseURL = new URL("http://www.java2s.com/abc/d.htm");
relativeURL = new URL(baseURL, "../a.htm");
System.out.println(relativeURL.toExternalForm());
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » URL URI