Share on Google+Share on Google+

Java file to url

In this section, you will learn how to convert file to url.

Java file to url

In this section, you will learn how to convert file to url.

Description of code:

The File class provides a method toURL() for this purpose. But if the path of file contains special characters link space or exclamation mark, then the problem will occur as this method just appends "file:/" at the starting of the file path and doesn't escape any special characters.

To overcome this problem, you can use the following code:

File.toURI().toURL() : it gives correct output, escaping special characters from the file path.

Here is the code:


public class FileTOURL {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/Java Examples/data.txt");

Through the use of file.toURI().toURL(), you can easily convert file to url whether there is a simple path or contains special characters.


file:/C:/Java Examples/data.txt


Posted on: September 8, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.