In this tutorial, we will see “How to convert a File to URL in Java ?” While converting java.io.File to java.net.URL, we are first converting File to a URI and then URI to a URL.
Convert a File to URL in Java...!!! Click To Tweet
Convert File to URL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | /** * Java code to convert File to a URL * @author Deepak Verma */ import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; public class FileToUrl_Example { public static void main(String[] args) throws MalformedURLException { File file; URI uri; URL url; file = new File("/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString"); if (file.exists() && file.isFile()) { System.out.println("PATH: \n" + file.getPath()); // Convert file to a URI uri = file.toURI(); System.out.println("\nURI: \n" + uri.toString()); // Convert URI to a URL url = uri.toURL(); System.out.println("\nURL: \n" + url.toString()); } else { System.out.println("File doesn't exist."); } } } |
Output:
1 2 3 4 5 6 7 8 | PATH: /Users/d33p4k/Documents/Techndeck/JavaPractice/InputString URI: file:/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString URL: file:/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString |
Convert a File to a URL in Java...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
Other Useful References: