How to obtain correct URI of a local file?

Viewed 466

To my great surprise, following snippet prints false on jdk1.8.0_u144

public class Tmp {
  public static void main(String[] args) {
    File f = new File(".");
    boolean result = f.toPath().toUri().toString().equals(f.toURI().toString());
    System.out.println("result = " + result);
  }
}

Obviously, java.io.File#toURI and java.nio.Path#toUri return different presentations. The question is, which of them is correct (according to RFC 8089)?

1 Answers

TLDR version: Both forms of the URI are correct according to RFC 8089. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Your sample code highlights the difference between the value returned by Path's toUri() and File's toURI() methods for a given file. Printing those to values on my Win10 machine showed:

path.toUri() => file:///D:/NetBeansProjects/MiscTests/./

file.toUri() => file:/D:/NetBeansProjects/MiscTests/./

The results on Linux are similar:

path.toUri() => file:///home/johndoe/IdeaProjects/TestUri/./

file.toUri() => file:/home/johndoe/IdeaProjects/TestUri/./

So the only difference is the single or triple forward slashes following "file:" in the URI.

From your link, Appendix B of RFC 8089 confirms that both forms are valid URIs:

A traditional file URI for a local file with an empty authority. This is the most common format in use today. For example:

  *  "file:///path/to/file"

o The minimal representation of a local file with no authority field and an absolute path that begins with a slash "/". For example:

  *  "file:/path/to/file"

Further confirmation that both URI forms are valid is that either can be entered in a browser to display the content of the directory. However, there are a few points worth noting:

  • Brave was the only browser that would not accept the single slash form of the URI (as given by File.toURI().toString()).

  • All browsers accepted the triple slash form of the URI (as given by File.toPath().toUri().toString()).

  • If I entered the URI in the browser's adddress bar with a single slash it was converted to a triple slash.

  • Strangely, both Chrome and Firefox will accept any number of slashes in the URI (e.g. file:///////////D:/NetBeansProjects/MiscTests/), and still display the directory.

Related