tags:

views:

634

answers:

4

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.

+1  A: 

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.

Jon Skeet
A: 

But an entry in a JAR file is not a File! The JAR file is a file; its entries are JAR-file entries (to state the obvious).

Java contains abstractions that mean you don't necessarily need to work with Files - why not use a Reader or InputStream to encapsulate the input?

oxbow_lakes
+1  A: 

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

Joachim Sauer
I actually do have a web server (Jetty) embedded in the application. Then problem is Desktop.browse(URI) will only launch a browser and not an application.
Steve Kuo
@Kuo: yes, I realized you asked about open() after I added my edit. Of course for open() only the temp file solution is useful.
Joachim Sauer
A: 
OscarRyz