Share on Google+Share on Google+

Java file from url

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

Java file from url

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

Description of code:

We have already told you the conversion of file to url in one of the previous sections. This is just reverse of that. You can see in the given example, we have created an object of URL class and specified an url string in the constructor of URL class. Now to convert this url to file, we have used the method getFile() of URL class. This method returns the string which is then passed into the constructor of File class. Using the method getPath() we have displayed the file on the console.

URL: This class represents a Uniform Resource Locator, a pointer to a resource on the World Wide Web.

getFile(): This method of URL class returns the file name of the URL.

getPath(): This method of File class  converts the abstract pathname into a pathname string.

Here is the code:


public class FileFromURL {
	public static void main(String[] args) throws Exception {
		String urlstring = "file:///C:/java/examples/data.txt";
		URL u = new URL(urlstring);
		String st = u.getFile();
		File f = new File(st);

Through the above you can convert any url to file.




Posted on: April 14, 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.