Java File.toURI and toPath
Pass a legacy File to NIO or produce a properly escaped file URL.
A simple example
File.toURI and toPath
- Start with Unix path /tmp/a b
- Do this Convert to a file URI
- Result Space becomes %20
Syntax
public URL toURL() throws MalformedURLException
JDK 21 declarations (3)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaAttach a receipt whose name contains a space
An older invoicing system gives the exporter a File object. The browser needs a URL with a correctly encoded space, while the new reporting code needs a Path for subsequent file operations.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
File invoice = new File("May sales.txt");
System.out.println(invoice.toURI().toURL().toExternalForm().endsWith("May%20sales.txt"));
System.out.println(invoice.toPath().getFileName());
}
}
true May sales.txt
The URI supplies the escaping rules and the Path retains the local filename.
Explain a broken link from an old catalog
An old catalog built file URLs directly from desktop filenames. Compare how the deprecated conversion and the URI-based conversion represent the space in a sample name before migrating those links.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
File paper = new File("Field notes.txt");
System.out.println(paper.toURL().toExternalForm().contains("Field notes.txt"));
System.out.println(paper.toURI().toURL().toExternalForm().contains("Field%20notes.txt"));
}
}
true true
The deprecated method leaves the space unescaped. The URI-based form expresses the same character as %20.
Share a score location
A music librarian exports a local link to a score with a space in its name. Turn the local path into a file URI. How is the space in the final filename represented?
What to watch for
File.toURL is deprecated because it does not reliably escape special characters. Use toURI().toURL() when a consumer needs a URL.