Java - How to convert File to URL

Posted on November 13, 2016


In this post, I will show you how to convert java.io.File to java.net.URL and vice versa.

The following example demonstrates the conversion of File to URL.

FileToUrlExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

/**
 * @author imssbora
 */
public class FileToUrlExample {
	public static void main(String[] args) {
		File file = new File("C:/Program Files/Java/jdk1.8.0_71/COPYRIGHT");
		if (file.exists()) {
			System.out.println("PATH: " + file.getPath());

			// Convert file to URI
			URI uri = file.toURI();
			System.out.println("URI: " + uri.toString());

			// Convert URI to URL
			URL url;
			try {
				url = uri.toURL();
				System.out.println("URL: " + url.toString());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}

		}
	}
}

Output

PATH: C:\Program Files\Java\jdk1.8.0_71\COPYRIGHT
URI: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT
URL: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT

 

The following example demonstrates the conversion of URL to File.

UrlToFileExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * @author imssbora
 */
public class UrlToFileExample {
	public static void main(String[] args) {
		try {
			URL url=new URL("file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT");
			System.out.println("URL: "+url.toString());
			
			//Convert URL to URI
			URI uri=url.toURI();
			System.out.println("URI: "+uri.toString());

			//Convert URI to File
			File file=new File(uri.getPath());
			System.out.println("PATH: "+file.getAbsolutePath());
			
		} catch (MalformedURLException | URISyntaxException e) {
			e.printStackTrace();
		}
	}
}

Output

URL: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT
URI: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT
PATH: C:\Program Files\Java\jdk1.8.0_71\COPYRIGHT