Java – How to Create Java Zip Archives with a Max File Size Limit

androidjava

I need to write an algorithm in java (for an android app) to read a folder containing more folders and each of those containing images and audio files so the structure is this: mainDir/subfolders/myFile1.jpg

  • It must be in java, something like perl script is not an option. It would preferably be for the compressed archive in order to squeeze as many files as possible before mailing the zip. Just a normal zip (no jar).

My problem is that I need to limit the size of the archive to 16mb and at runtime, create as many archives as needed to contain all my files from my main mainDir folder. I tried several examples from the net, I read the java documentation, but I can't manage to understand and put it all together the way I need it.

Has someone done this before or has a link or an example for me? I resolved the reading of the files with a recursive method but I can't figure the logic for the zip creation.

EDIT: FileNotFoundException (no such file or directory) this was my initial post at Stack Overflow. I've got an answer to it, but I can't set the size of the ZipEntry and the logic doesn't work and also when extracting the my files from the zip I get the compression method not supported error.

Best Answer

The size limit (16 mb or whatever) does not enforce you to have archive size as close to it as possible.

Assuming that you are allowed to create archives of smaller size, here is the "first iteration" solution - dead simple, but meets your requirements: just zip every file into separate archive.

  1. myFile1 -> archive1.zip
  2. myFile2 -> archive2.zip
  3. etc

Now, if you want it a bit less dumb, use the sum of current archive size (Deflater.getBytesWritten()) and next uncompressed file size to decide if it's time to switch to creating new archive.

  1. myFile1 -> archive1.zip
  2. size of archive1.zip plus myFile2 within limit -> add myFile2 to archive1
  3. size of archive1.zip plus myFile3 exceeds limit -> add myFile3 to new zip, archive2
    Yeah there is a chance that adding compressed myFile3 to archive1 will remain within limit, but why bother?
  4. etc
Related Topic