In Java, there can be a situation to include a file path in the URL automatedly. This requires the file path(s) to be transformed into URL format first. It is done since the formats of both the file path and URL are entirely different. Therefore, passing/converting a local file into a URL is of great aid in locating and using the target/required file.
This article will discuss the approaches to passing a local file into a URL in Java.
How to Pass a Local File into URL in Java?
To pass a local file into a URL in Java, the combined “toURI()” and “toURL()” methods of the “File” class are used. These methods transform the target file into the corresponding URL.
Syntax
public URI toURI() throws URISyntaxException
This method returns a URI instance equivalent to this URL.
Thrown Exception
This method throws/returns the “URISyntaxException” if this URL is not formatted strictly.
Before proceeding with the demonstration, import the following packages in it to work with the “File” and “URL” classes and handle the “MalformedURLException”:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
Example: Pass/Transform a Local File into a URL in Java
This example converts the specified file into a URL:
public class LocalfileURL {
public static void main(String[] args) throws MalformedURLException {
File readFile = new File("readfile.txt");
System.out.println("Absolute File Path -> "+readFile.getAbsolutePath());
URL resultUrl = readFile.toURI().toURL();
System.out.println("URL of the File -> "+resultUrl);
}}
In this snippet of code:
- Firstly, handle the “MalformedURLException” that implies that a malformed URL has been faced.
- Also, create a File object utilizing the “new” keyword and the “File()” constructor.
- After that, apply the “getAbsolutePath()” method that returns the absolute pathname of the target file object.
- Now, apply the combined “toURI()” and “toURL()” methods to transform the specified local path into a URL and display the resultant URL.
Output

As observed, the passed file path is converted into a URL appropriately.
Conclusion
To pass or convert a local file into a URL in Java, the combined “toURI()” and “toURL()” methods of the “File” class are utilized. These methods assist in retrieving the corresponding URL against the provided file path. This tutorial explained the approach to passing a local file into a URL in Java.