In this tutorial, we will see “How to convert File to URL and vice versa in Java ?” While converting File to URL, we are first converting File to a URI and then URI to a URL. Similarly, while converting URL to a File, we convert URL to URI first and then URI to a File.

Convert File to URL and vice versa in Java...!!! Share on X

Example 1. Convert File to URL

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:

PATH: 
/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString

URI: 
file:/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString

URL: 
file:/Users/d33p4k/Documents/Techndeck/JavaPractice/InputString

 

Example 2. Convert URL to File

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

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts