How do I get a URL or URI to a file?
Author: Deron Eriksson
Description: This Java tutorial describes how to get a URL or URI to a file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


If you have a File object, you can obtain a URI to the file by calling the toURI() method on the file. In general, although the File object has a toURL() method, this method doesn't handle special character conversion, so in general it's best to call toURI().toURL() to get a URL to the file, since this will handle special character conversions. This is demonstrated with the FileUriAndUrl class:

FileUriAndUrl.java

package test;

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

public class FileUriAndUrl {

	public static void main(String[] args) throws IOException {

		File file = new File("file name with spaces.txt");

		URI fileUri = file.toURI();
		System.out.println("URI:" + fileUri);

		URL fileUrl = file.toURI().toURL();
		System.out.println("URL:" + fileUrl);

		URL fileUrlWithoutSpecialCharacterHandling = file.toURL();
		System.out.println("URL (no special character handling):" + fileUrlWithoutSpecialCharacterHandling);

	}

}

The output of FileUriAndUrl is shown below. As you can see, file.toURI() handles special character conversions while file.toURL() does not, so in general calling file.toURI().toURL() is a better course of action.

URI:file:/C:/projects/workspace/testing/file%20name%20with%20spaces.txt
URL:file:/C:/projects/workspace/testing/file%20name%20with%20spaces.txt
URL (no special character handling):file:/C:/projects/workspace/testing/file name with spaces.txt