javajava-20

How to replace the deprecated URL constructors in Java 20?


All URL constructors are deprecated in Java 20. I replaced new URL(protocol, host, file) by new URI(protocol, host, file, null).toURL() as I have no query and no fragment but I don't know what to do with the others:

/home/gouessej/Documents/programmation/java/workspace/Ardor3D/ardor3d-core/src/main/java/com/ardor3d/util/UrlUtils.java:40: warning: [deprecation] URL(String) in URL has been deprecated
        return new URL(new URL(url), relativeLoc);
                       ^
/home/gouessej/Documents/programmation/java/workspace/Ardor3D/ardor3d-core/src/main/java/com/ardor3d/util/UrlUtils.java:40: warning: [deprecation] URL(URL,String) in URL has been deprecated
        return new URL(new URL(url), relativeLoc);
               ^
/home/gouessej/Documents/programmation/java/workspace/Ardor3D/ardor3d-core/src/main/java/com/ardor3d/util/resource/SimpleResourceLocator.java:94: warning: [deprecation] URL(URL,String) in URL has been deprecated
            final URL rVal = new URL(_baseDir.toURL(), spec);
                             ^
/home/gouessej/Documents/programmation/java/workspace/Ardor3D/ardor3d-audio/src/main/java/com/ardor3d/audio/FilenameURL.java:125: warning: [deprecation] URL(String) in URL has been deprecated
                    url = new URL( filename );

Would simply new URI(filename).toURL()do the job in the last case?

When I compare the wording in the Java documentation, I understand that an URI scheme means more or less a URL protocol, an URI host is an URL host and an URL file matches with a URI path and an optional URI query. What are the exact equivalent of new URL(spec) and new URL(context, spec)?

I prepared some suggested changes but it doesn't work, an IllegalArgumentException is thrown.


Solution

  • tl;dr

    Ex: URI uri = Paths.get( "/Users/your_user_name/example.txt" ).toUri() ;

    Details

    Understand that:

    Read this note from the Java team, Oracle: Quality Outreach Heads-up - JDK 20: Deprecate URL Public Constructors. To quote:

    JDK 20 will deprecate all public constructors of java.net.URL. … To construct a URL, the URI::toURL alternative should instead be preferred. To construct a file: based URL, Path::toURI should be used prior to URI::toURL.

    And see the note on constructor deprecation within the Javadoc of URL class.

    See also the issue-tracker page, JDK-8294241 Deprecate URL public constructors.

    Example: File path URI

    For working with files in modern Java, use NIO.2 features.

    1. The Paths class can produce a Path object.
    2. From there, ask that Path to produce a URI.
    Path path = Paths.get( "/Users/your_user_name/example.txt" ) ;
    URI uri = path.toUri () ;
    

    uri.toString() = file:///Users/your_user_name/example.txt

    Going the other direction:

    Path path = Paths.get( uri ) ;