1

How to zip specific file in android? for example I only want to zip random file in my phone storage like video.mp4, music.mp3, word.docx, image.jpeg. i tried to search the same question here and they always say that try this link Zipping Files with Android (Programmatically) but the page is already not found. do you have alternative link for this?

Thank you in advance! I appreciate it.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
asgardwin7
  • 127
  • 1
  • 2
  • 13

1 Answers1

5

Take a look at ZipOutputStream

You open a new FileOutputStream to write a file, followed by a ZipOutputStream to write a ZIP. Then you create ZipEntrys for every file you want to zip and write them. Don't forget to close the ZipEntrys and the streams.

For example:

// Define output stream
FileOutputStream fos = new FileOutputStream("zipname.zip");
ZipOutputStream zos = new ZipOutputStream(fos);

// alway use a try catch block and close the zip in the finally
try {
    ZipEntry zipEntry = new ZipEntry("entryname.txt");
    zos.putNextEntry(zipEntry);
    // write any content you like
    zos.write("file content".getBytes());
    zos.closeEntry();
}
catch (Exception e) {
    // unable to write zip
}
finally {
    zos.close();
}

Hope it helped!

clfaster
  • 1,450
  • 19
  • 26