Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a folder from JAR

Tags:

java

I need to copy a folder, packed in a Jar on runtime. I want to do it by calling a function in a class which is also contained in the same folder.

I've tried using getSystemResource:

URL sourceDirUrl = ClassLoader.getSystemResource("sourceDirName"); 
File sourceDir = new File(sourceDirUrl.toURI());

but it doesn't work. I probably have to use getResourceAsStream function recursively. Is there a more elegant/strait-forward way to do this?

In case I have to do it recursively: 1. I don't want to specify the files hard-coded, I want to do it dynamically 2. I don't want to create a separate archive. I want this resource to be in the same Jar as the classes dealing with it

Thanks

I ended up doing what Koziołek suggested below. Although I was hoping for a more elegant solution, but it looks like this is as good as it gets.

like image 510
Leonid B Avatar asked Mar 21 '11 11:03

Leonid B


2 Answers

Using the classloader you cannot retrieve a folder as it can not be a resource of your classpath.

Several solutions are possible:

  • Using the classloader getResource method, retrieve all resources of your folder one by one if you know in advance the file names you are looking for.
  • Pack your complete folder into an archive that you can retrieve from the classloader using the previous method.
  • Unzip your jar directly to retrieve the contained folder. It requires to know the precise location of the jar from the filesystem. This is not always possible depending on the application and is not portable.

I would preferably going for the second solution that is more portable and flexible but requires to repack the archive for all modifications of the folder content.

like image 73
greydet Avatar answered Nov 05 '22 21:11

greydet


Jar is simple ZIP file. You can use java.util.zip.* package to decompress files.

like image 2
Koziołek Avatar answered Nov 05 '22 22:11

Koziołek