Java tutorial
//package com.java2s; //License from project: Apache License import android.util.*; import java.io.*; import java.util.zip.*; public class Main { public static void compressAFileToZip(File zip, File source) throws IOException { Log.d("source: " + source.getAbsolutePath(), ", length: " + source.length()); Log.d("zip:", zip.getAbsolutePath()); zip.getParentFile().mkdirs(); File tempFile = new File(zip.getAbsolutePath() + ".tmp"); FileOutputStream fos = new FileOutputStream(tempFile); BufferedOutputStream bos = new BufferedOutputStream(fos); ZipOutputStream zos = new ZipOutputStream(bos); ZipEntry zipEntry = new ZipEntry(source.getName()); zipEntry.setTime(source.lastModified()); zos.putNextEntry(zipEntry); FileInputStream fis = new FileInputStream(source); BufferedInputStream bis = new BufferedInputStream(fis); byte[] bArr = new byte[4096]; int byteRead = 0; while ((byteRead = bis.read(bArr)) != -1) { zos.write(bArr, 0, byteRead); } zos.flush(); zos.closeEntry(); zos.close(); Log.d("zipEntry: " + zipEntry, "compressedSize: " + zipEntry.getCompressedSize()); bos.flush(); fos.flush(); bos.close(); fos.close(); bis.close(); fis.close(); zip.delete(); tempFile.renameTo(zip); } public static void close(Closeable closable) { if (closable != null) { try { closable.close(); } catch (IOException e) { e.printStackTrace(); } } } public static boolean delete(File file) { file.setWritable(true); try { if (!file.delete()) { FileOutputStream fos = new FileOutputStream(file); fos.write(0); fos.flush(); fos.close(); } Log.d("delete", "Deleted file: " + file + " successfully"); return true; } catch (IOException e) { Log.d("delete", "The deleting file: " + file + " is not successfully", e); return false; } } private static void delete(File file, StringBuilder sb) { long length = file.length(); boolean deleted = file.delete(); if (deleted) { sb.append(file.getAbsolutePath() + " length " + length + " bytes, deleted.\r\n"); } else { sb.append(file.getAbsolutePath() + " length " + length + " bytes, can't delete.\r\n"); } } }