Convert local file path to URL & URI in java (example)

By | February 16, 2017
  • Given a File in java.
  • We would like to convert path of a file to URL & URI path.
    • e.g. If path of file on local windows operating system is “D:\Code\Local File Path.txt”
    • URL & URI of local file path will be “file:/D:/Code/Local%20File%20Path.txt”
  • We will use toURL() and toURI() method of File class .

1. Program: convert local file path to URL & URI in java (example)

package org.learn.io;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class FilePathToURL_URI {
    public static void main(String[] args) throws MalformedURLException {
        File file = new File("Local File Path.txt");

        System.out.println("1. Absolute file path :"+file.getAbsolutePath());

        //Convert local path to URL
        URL url = file.toURI().toURL();
        System.out.println("2. URL of given file is:"+url);

        //Convert local path to URI
        URI uri = file.toURI();
        System.out.println("3. URI of given file is:"+uri);
    }
}

2. Output: convert local file path to URL & URI in java (example)

1. Absolute file path :D:\Code\Local File Path.txt
2. URL of given file is:file:/D:/Code/Local%20File%20Path.txt
3. URI of given file is:file:/D:/Code/Local%20File%20Path.txt