Library contents

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

  1. Start with Unix path /tmp/a b
  2. Do this Convert to a file URI
  3. Result Space becomes %20
A URI encodes the space while retaining the underlying filename.

Syntax

Java 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.java

Send 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.

From the programPath receipt = Path.of("March orders.txt").toAbsolutePath()
First output linetrue
Main.java
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"));
    }
}
Output
true
March orders.txt
true

URI encoding preserves the space across a link. The local filename retains its original spelling.

Advertisements

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.

From the programPath item = Path.of("lab notes.txt").toAbsolutePath()
Resulttrue
Main.java
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));
    }
}
Output
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?

GivenChoir A.pdf
Worked resultChoir%20A.pdf

What to watch for

Only paths from the default file system are required to support conversion to java.io.File.

Documentation for Path.toUri and toFile