URL Relative

In this chapter you will learn:

  1. Resolve a relative URL
  2. How to resolve a parent file

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:

  1. How to check the legal protocol
Home » Java Tutorial » URL URI
URL
URL Creation
URL for jar file
URL Components
Convert file path to URL
URL Relative
URL Protocol
Read from URL
Compare URL
URLConnection
HTTP Header
URLConnection Post
Cookie
URLConnection Read
HttpURLConnection
HttpURLConnection Properties
HttpURLConnection proxy
HttpURLConnection Authenticator
HTTPS
JarURLConnection
Encode a URL
Decode a URL
URI
URI Normalization
URI Resolution
URI Relativization
Convert URI to URL
IP Address
IP Ping
NetworkInterface