views:

2381

answers:

3

I have a J2EE app deployed as an EAR file, which in turn contains a JAR file for the business layer code (including some EJBs) and a WAR file for the web layer code. The EAR file is deployed to JBoss 3.2.5, which unpacks the EAR and WAR files, but not the JAR file (this is not the problem, it's just FYI).

One of the files within the JAR file is an MS Word template whose absolute path needs to be passed to some native MS Word code (using Jacob, FWIW).

The problem is that if I try to obtain the File like this (from within some code in the JAR file):

URL url = getClass().getResource("myTemplate.dot");
File file = new File(url.toURI()); // <= fails!
String absolutePath = file.getAbsolutePath();
// Pass the absolutePath to MS Word to be opened as a document

... then the java.io.File constructor throws the IllegalArgumentException "URI is not hierarchical". The URL and URI both have the same toString() output, namely:

jar:file:/G:/jboss/myapp/jboss/server/default/tmp/deploy/tmp29269myapp.ear-contents/myapp.jar!/my/package/myTemplate.dot

This much of the path is valid on the file system, but the rest is not (being internal to the JAR file):

G:/jboss/myapp/jboss/server/default/tmp/deploy/tmp29269myapp.ear-contents

What's the easiest way of getting the absolute path to this file?

+3  A: 

My current solution is to copy the file to the server's temporary directory, then use the absolute path of the copy:

File tempDir = new File(System.getProperty("java.io.tmpdir"));
File temporaryFile = new File(tempDir, "templateCopy.dot");
InputStream templateStream = getClass().getResourceAsStream("myTemplate.dot");
IOUtils.copy(templateStream, new FileOutputStream(temporaryFile));
String absolutePath = temporaryFile.getAbsolutePath();

I'd prefer a solution that doesn't involve copying the file.

Andrew Swan
+1  A: 

Unless the code or application you are passing the URI String to accepts a format that specifies a location within a jar/zip file, your solution of copying the file to a temporary location is probably the best one.

If these files are referenced often, you may want to cache the locations of the extract files and just verify their existance each time they are needed.

Chris Thornhill
Thanks Chris. I'm pretty sure Word needs an absolute path, and would be confused by a JAR/ZIP-style path. I am indeed lazy-copying the original file to the temp folder, I just left that out of my answer for the sake of brevity.
Andrew Swan
A: 

You should copy the contents to a temporary file (potentially with a cache), because trying to get to internal files of the application container is a dependency you want to avoid. There may not even be an extracted file at all (it can load from the JAR directly).

Thilo