Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the absolute path of a file within a JAR within an EAR?

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?

like image 503
Andrew Swan Avatar asked Apr 27 '09 00:04

Andrew Swan


People also ask

How do I get the path of a jar file?

jar” part, convert it back to a URL object, and use the Paths class to get the path as a String. We build a regex and use String's replaceAll() method to extract the part we need: String path = url. replaceAll(“^jar:(file:. *[.]

What is absolute path of a file in Java?

An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

How do JAR files work?

JAR files are packaged with the ZIP file format, so you can use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking. These tasks are among the most common uses of JAR files, and you can realize many JAR file benefits using only these basic features.


1 Answers

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.

like image 105
Andrew Swan Avatar answered Oct 05 '22 15:10

Andrew Swan