Reputation: 63094
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.
Upvotes: 7
Views: 9071
Reputation: 199234
No, it is not, because as you just witness you don't have a valid file in first place
From the article: Using the Desktop API in Java SE 6 we got
OPEN: Represents an open action performed by an application associated with opening a specific file type
So you would have to have a valid file and then have an application associated with that file so the OS can open it. While such app may exist you still have to make it understand the URL to your file.
Upvotes: 0
Reputation: 308061
"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.
Upvotes: 6
Reputation: 134280
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 File
s - why not use a Reader
or InputStream
to encapsulate the input?
Upvotes: 1
Reputation: 1501033
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.
Upvotes: 3