I have a web app which depends on some jar. The jar is in a WEB-INF/lib
folder. At runtime I need to copy the jar to another folder and then extract it. Is there any ways to this?

- 389,944
- 63
- 907
- 827

- 4,462
- 7
- 42
- 70
-
Not simply by having the jar in the classpath, no. Why do you want to do this? – John Bollinger Oct 08 '14 at 14:48
-
Add the jar as a "Add class folder", then you dont need to extract it explicitly. – Sireesh Yarlagadda Oct 08 '14 at 14:48
2 Answers
You can use ServletContext.getRealPath()
to get real paths of virtual paths.
For example to get the webapp's WEB-INF/lib
folder:
File libFolder = new File(ServletContext.getRealPath("/"), "WEB-INF/lib");
To get a specific jar file:
File jarFlie = new File(libFolder, "somejar.jar");
Jar files are normal zip files. You can extract it just like any other zip files. See ZipFile
and JarFile
for details.

- 389,944
- 63
- 907
- 827
I am not sure in which context you try to do this. If you are in a Spring application or something else it might be a bit different to what I describe here.
If you are in the context of a Servlet you could just facilitate the Java ClassLoader or to be more precise the class loader of your runtime environment in your case most likely an application server such as Tomcat or Glassfish to get a stream to read the JAR file e.g.
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/lib/yourlib.jar");
You will get an InputStream that you can use to read the file. You can then use the Apache Commons FileUtils to copy the Stream to another file.
File outputFile = File.createTempFile("temp-file-name", ".jar");
FileUtils.copyInputStreamToFile(in, outputFile);
In the example above I put code that writes to a temporary directory. I cannot answer which application server will actually allow you to write to arbitrary filesystem locations and which one will not. So I assume that writing to a temporary directory should be allowed in every environment.
For your last step. Actually extracting the JAR file I would like to refer you to this post which is an excellent explanation of how to extract JAR/ZIP files from Java code.
Of course you will need to adapt the examples given there to again write your files to a location where you are positive you can actually write.

- 1
- 1

- 1,786
- 11
- 24