Is it possible to exclude files and/or directories when using GZIPOutputStream or ZIPOutputStream in java?

1.3k views Asked by At

I am trying to archive all the files in the root directory of the folder but have the backups as one of the folders in the root directory so I wanted to exclude it so each backup after the first one isn't backing up the backups folder (aka increasing the size of the archive exponentially) in java, If it is not possible with GZIPOutputStream or ZIPOutputStream could you recommend me an alternative method for backing up files that allows excluding files and/or directories from the backup? Thank you for reading!

1

There are 1 answers

6
Fullslack On BEST ANSWER

To be able to exclude certain files or folders from a Zip or GZip you have two options:

  1. Loop over all the files/folders and exclude any files/folders you don't want to have inside the zip.
  2. Use a zip package like zip4j. This allows you to exclude certain files with a filter.
List<File> filesToExclude = Arrays.asList(new File("/full/path/to/folder_to_add/sample.pdf"), new File("/full/path/to/folder_to_add/subfolder/sample_2.txt"), new File("/full/path/to/folder_to_add/subfolder_to_exclude"));
ExcludeFileFilter excludeFileFilter = filesToExclude::contains;
ZipParameters zipParameters = new ZipParameters();
zipParameters.setExcludeFileFilter(excludeFileFilter);
new ZipFile("filename.zip").addFolder(new File("/full/path/to/folder_to_add"), zipParameters); // On Windows you need to include drive letter as well

Don't forget to include the driveletter (ie: C:) on Windows systems.

You can see that it is also possible to exclude complete folders, not only files. But the full (or relative) path to file/folder is necessary!

Edit: not only is the documentation missing the filesToExclude list definition, it is also unclear about the absolute path requirements for all new File() calls. Updated answer to reflect this. You either need to use a absolute path or a relative path. Relative path are made with the . prepend. Current example is tested and working on Windows 10.