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

  • Given a local file present on our file system.
  • We would like to convert path of a file to URL & URI path.
    • e.g. If path of file on windows operating system is “D:\Code\LocalFilePath.txt”
    • URL & URI of local file path will be “file:/D:/Code/LocalFilePath.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("LocalFilePath.txt");

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

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

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

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

1. Absolute file: D:\Code\LocalFilePath.txt
2. URL of given file is: file:/D:/Code/LocalFilePath.txt
3. URI of given file is: file:/D:/Code/LocalFilePath.txt
Scroll to Top