Convert File to URI /URL - Java Example

This example discusses briefly the various options to convert a File to URI string in Java. I thought of writing a post on this as we got a compile time warning on the code, that converted SVG to JPG earlier. The warning is provided below:
svg2jpg.java:8: warning: [deprecation] toURL() in File has been deprecated
        String svg_URI_input = new File("chessboard.svg").toURL().toString();

When I read the Oracle documentation about this, there is a note against this method. I’m producing the note again for a quick reference [ Reference : Oracle Docs ]

Deprecated. This method does not automatically escape characters that are illegal in URLs.
It is recommended that new code convert an abstract pathname into a URL by first converting it into a URI, via the toURI method,
and then converting the URI into a URL via the URI.toURL method.

In this post, we will discuss various options to avoid the warning message.

Convert File to URI, then to URL and then to String

A code snippet that does that is provided below:

        /* Code changed as toURL is deprecated against File */
        String svg_URI_input = new File("chessboard.svg").toURI().toURL().toString();


Java NIO for File to URI

You can use “Paths” in Java NIO to get URI and convert it into a string, for the same code. An example is provided below:


import java.nio.file.Paths;
import java.nio.file.Path;
String svg_URI_input = Paths.get("chessboard.svg").toUri().toURL().toString();

Hope this tutorial would have given you some ideas to convert a File to URL by using both Java.IO and the NIO approaches. If you have a different way to do it, you can post it in the comments section.

No comments:

Post a Comment