Convert file path to URL

In this chapter you will learn:

  1. How to convert file path to URL

Convert file path to URL

The following code calls the file.URL().toURL() to convert a file path to a URL.

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
/*from j a  v a  2s .  c o  m*/
public class Main {
  public static void main(String[] argv)throws MalformedURLException {
    URL url = convertFileToURL( "c:/abc/def.htm");
    System.out.println(url);
  }
  public static URL convertFileToURL( String filePath ) throws MalformedURLException {
      File file = new File(filePath.trim());
      return file.toURI().toURL();
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Resolve a relative URL
  2. How to resolve a parent file
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