Java Desktop.open(File f) reference file within JAR?

desktop, jar, java

Solution

"Files" inside .jar files are not files to the operating system. They are just some area of the .jar file and are usually compressed. They are not addressable as separate files by the OS and therefore can't be displayed this way.

Java itself has a neat way to referring to those files by some URI (as you realized by using `getResource()`) but that's entirely Java-specific.

If you want some external application to access that file, you've got two possible solutions:

- Provide some standardized way to access the file or

- Make the application able to address files that are packed in a .jar (or .zip) file.

Usually 2 is not really an option (unless the other application is also written in Java, in which case it's rather easy).

Option 1 is usually done by simply writing to a temporary file and referring to that. Alternatively you could start a small web server and provide the file via some URL.

Problem

It is possible to for `Desktop.open(File f)` to reference a file located within a JAR? I tried using `ClassLoader.getResource(String s)`, converting it to a URI, then creating a File from it. But this results in `IllegalArgumentException: URI is not hierarchical`. ``` URL url = ClassLoader.getSystemClassLoader().getResource(...); System.out.println("url=" + url); // url is valid Desktop.getDesktop().open(new File(url.toURI())); ``` A possibility is the answer at JavaRanch, which is to create a temporary file from the resource within the JAR – not very elegant. This is running on Windows XP.

Original source