In this tutorial, we will see “How to convert a URL to File in Java ?” While converting java.net.URL to java.io.File, we are first converting URL to a URI and then URI to a File.
Convert URL to File in Java...!!! Share on X
Convert URL to File
/**
* Java code to convert a URL to a File
* @author Deepak Verma
*/
import java.io.File;
import java.net.URI;
import java.net.URL;
public class UrlToFile_Example {
public static void main(String[] args) {
File file;
URI uri;
URL url;
try {
url = new URL("file:/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString");
System.out.println("URL: \n" + url.toString());
//Convert URL to a URI
uri = url.toURI();
System.out.println("\nURI: \n" + uri.toString());
//Convert URI to a File
file = new File(uri.getPath());
System.out.println("\nPATH: \n" + file.getAbsolutePath());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output:
URL: file:/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString URI: file:/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString PATH: /Users/d33p4k/Documents/Techndeck/JavaPractice/InputString
Convert URL to a File in Java...!!! Share on X
Do you like this Post? – then check my other helpful posts:
Other Useful References: