Library contents

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

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

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

First output linetrue
Main.java
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());
    }
}
Output
true
May sales.txt

The URI supplies the escaping rules and the Path retains the local filename.

Advertisements

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.

First output linetrue
Main.java
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"));
    }
}
Output
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?

GivenChoir A.pdf
Worked resultChoir%20A.pdf

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.

Documentation for File.toURI and toPath