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.
What you could do is to use getResourceAsStream() method with the directory path, and the input Stream will have all the files name from that dir. After that you can concat the dir path with each file name and call getResourceAsStream for each file in a loop.
JAR files are packaged in the ZIP file format. The unzip command is a commonly used utility for working with ZIP files from the Linux command-line. Thanks to the unzip command, we can view the content of a JAR file without the JDK.
Given an actual JAR file, you can list the contents using JarFile. entries() .
"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:
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.
A resource within a jar file simply isn't a file - so you can't use a File
to get to it. If you're using something which really needs a file, you will indeed have to create a temporary file and open that instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With