Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a file in a specific folder (in the ZIP)

Tags:

java

zip4j

The following code, how to add a file to a zip using java:

String source = "C:/Users/XXXXX/Desktop/Helicopter.zip";
try {
  ZipFile zipFile = new ZipFile(source);

  ZipParameters parameters = new ZipParameters();

  zipFile.addFile(new File("C:/Users/XXXXXX/Desktop/HELLO_HELICOPTER.txt"), parameters);


} catch (net.lingala.zip4j.exception.ZipException e) {
  e.printStackTrace();
}

How am I able to add the file in a specific folder in this zip-archive?

like image 410
codepleb Avatar asked Oct 20 '25 21:10

codepleb


1 Answers

To maintain the original folder structure in zip file created by net.lingala.zip4j.ZipFile:

ZipFile zipFile = new ZipFile("target/new.zip");
ZipParameters zipParameters = new ZipParameters();
zipParameters.setFileNameInZip("folder/subfolder/file-name.txt");

zipFile.addFile(new File("folder/subfolder/file-name.txt"), zipParameters);

If not setting the zipParameters.setFileNameInZip the file is added in root of the zip file without the original directory structure.

like image 84
PrecisionLex Avatar answered Oct 23 '25 11:10

PrecisionLex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!