Interoperability with the java.net.URI Class – Java I/O: Part II

Interoperability with the java.net.URI Class

A URI consists of a string that identifies a resource, which can be a local resource or a remote resource. Among other pertinent information, a URI specifies a scheme (e.g., file, ftp, http, and https) that indicates what protocol to use to handle the resource. The examples of URIs below show two schema: file and http. We will not elaborate on the syntax of URIs, or different schema, as it is beyond the scope of this book.

Click here to view code image

file:///a/b/c/d                      // Scheme: file, to access a local file.
http://www.whatever.com              // Scheme: http, to access a remote website.

Click here to view code image

URI(String str) throws URISyntaxException
static URI create(String str)

This constructor and this static method in the java.net.URI class create a URL object based on the specified string. The second method is preferred when it is known that the URI string is well formed.

Click here to view code image

// Create a URI object, using the URL.create(String str) static factory method.
URI uri1 = URI.create(“file:///a/b/c/d”);   // Local file.

The following methods can be used to convert a URI object to a Path object. The Paths.get(URI uri) static factory method actually invokes the Path.of(URI uri) static factory method.

Click here to view code image

// URI –> Path, using the Path.of(URI uri) static factory method.
Path uriToPath1 = Path.of(uri1);       // /a/b/c/d
// URI –> Path, using the Paths.get(URI uri) static factory method.
Path uriToPath2 = Paths.get(uri1);     // /a/b/c/d

The following method in the Path interface can be used to convert a Path object to a URI object:

Click here to view code image

// Path –> URI, using the Path.toUri() instance method.
URI pathToUri = uriToPath1.toUri();    // file:///a/b/c/d

Interoperability between a Path object and a URI object allows an application to leverage both the NIO.2 API and the network API.