[FIXED] "jar:file" vs. only "file:" reference when retrieving resources in Java

Issue

This question is related to my question

Jetty 11.0.11 – 404 on html file in \src\main\webapp\static – maven embedded fat jar

What –EXACTLY– does "jar:file" mean as a Java resource reference, vs. just "file:"?

And how is that influenced by the operating system ran under?

E. g. using this resource reference in Jetty webserver, in Windows with Oracle JDK 17, files are found as resources and parsed by Jetty webserver:

file:///D:/Projects/verdi_2/target/classes/static/,AVAILABLE}{file:/D:/Projects/verdi_2/target/classes/static}

Using this resource reference in Jetty webserver, in Ubuntu Linux 20.04 LTS with Oracle JDK 17, NO files are found and nothing can be parsed by Jetty webserver:

jar:file:/usr/src/verdi/verdi-12-JDK17-jar-with-dependencies.jar!/static

Is there a difference in how a Linux version of JDK interprets "jar:file" vs. how a Windows version of the JDK interprets "jar:file"?

EDIT: The related issue is the Jetty webserver apparently can no longer serve resources directly out of a JAR file it is itself embedded in. This is now a GitHub bug ticket at https://github.com/eclipse/jetty.project/issues/8549

Solution

file: is the beginning of a general file url. jar:file: is that for a jar file particularly, with a view to referring (usually) to a particular entry in a jar. Here’s an example you can run (obviously with your own jar url) where you can save an entry as a file (given by the parameter to the app)

import java.nio.file.Paths;
import java.nio.file.Files;
import java.net.URL;

public class JarUrl {
    public static void main(String[] args) {
        try {
            URL url = new URL("jar:file:root.jar!/root/a/b.txt");
            Files.copy(url.openStream(), Paths.get(args[0]));
        }
        catch(Throwable t) {
            t.printStackTrace();
        }
    }
}

Answered By – g00se

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published