Java file to url


 

Java file to url

In this section, you will learn how to convert 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:

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

Ads