Java Path.toUri and toFile
Convert a local path into a file URI, a legacy File object, or display text.
A simple example
Path.toUri and toFile
- Start with Unix path /tmp/a b
- Do this Convert to a file URI
- Result Space becomes %20
Syntax
URI toUri()
JDK 21 declarations (3)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSend a report location to an older desktop application
The archive screens use Path while an older attachment picker still takes File. A receipt name contains a space, so the exported URI also needs the correct escaping.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path receipt = Path.of("March orders.txt").toAbsolutePath();
System.out.println(receipt.toUri().toASCIIString().endsWith("March%20orders.txt"));
System.out.println(receipt.toFile().getName());
System.out.println(receipt.toString().endsWith("March orders.txt"));
}
}
true March orders.txt true
URI encoding preserves the space across a link. The local filename retains its original spelling.
Round-trip a local link with a space
A desktop catalog stores an absolute file URI and later reconstructs a Path from that URI. Verify the round trip with a name containing a space before using the address in a saved entry.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path item = Path.of("lab notes.txt").toAbsolutePath();
System.out.println(Path.of(item.toUri()).equals(item));
}
}
true
The file URI carries enough information to rebuild this local absolute path.
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
Only paths from the default file system are required to support conversion to java.io.File.