Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jar

desktop

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.

like image 886
Steve Kuo Avatar asked Oct 12 '09 18:10

Steve Kuo


People also ask

How can I access a folder inside of a resource folder from inside my JAR file?

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.

How do I view files in a JAR file?

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.

How do I get a list of files in a JAR file?

Given an actual JAR file, you can list the contents using JarFile. entries() .


2 Answers

"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:

  1. Provide some standardized way to access the file or
  2. 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.

like image 58
Joachim Sauer Avatar answered Oct 04 '22 01:10

Joachim Sauer


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.

like image 37
Jon Skeet Avatar answered Oct 04 '22 02:10

Jon Skeet