Home Tutorial Java Core Files Java file to url

 
 

Share on Google+Share on Google+
Java file to url
Posted on: September 8, 2006 at 12:00 AM
Advertisement
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:

import java.io.*;

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

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

Output:

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

Advertisement

Related Tags for Java file to url:


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.

Posted on: September 8, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com