4

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?

codepleb
  • 10,086
  • 14
  • 69
  • 111

2 Answers2

7

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.

PrecisionLex
  • 801
  • 11
  • 26
  • This solution is better in my opinion, you don't have to copy or move some files in a folder to generate the same structure in your zip archive, instead your file structure remains untouched and only the file structure in your archive is altered. – user2267367 Jun 14 '21 at 09:50
  • not that intuitive, but this works well – jediwompa Jan 05 '22 at 21:30
  • If you have a group of files that need to be added at the same folder level, then you can do `zipParameters.setRootFolderInZip` – jediwompa Jan 06 '22 at 01:34
5

I found the solution:

Put the file you want to add in a specific folder and then use the method "addFolder()".

All files within this folder will be added and if the same named folder is already in the zip, your folder will not be re-created, but the files will be added to the existing one

Example:

ZipFile zipFile = new ZipFile(source);
ZipParameters parameters = new ZipParameters();

zipFile.addFolder(new File("C:/Users/XXXXXX/Desktop/HELLO_Folder"), parameters);
codepleb
  • 10,086
  • 14
  • 69
  • 111