Here you can find the source of zip(File file, String dest)
Parameter | Description |
---|---|
file | a parameter |
dest | Where the zipped file will be stored |
public static File zip(File file, String dest)
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**// ww w. j a v a 2 s . co m * * @param file * @param dest * Where the zipped file will be stored * @return zipped file */ public static File zip(File file, String dest) { File zippedFile = new File(dest + "/" + file.getName() + ".zip"); try { FileOutputStream ops = new FileOutputStream(zippedFile); ZipOutputStream zos = new ZipOutputStream(ops); zip(file, zos, ""); zos.close(); } catch (FileNotFoundException fnfex) { fnfex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } return zippedFile; } public static ZipOutputStream zip(File file, ZipOutputStream zos, String prefix) { File[] entries = file.listFiles(); for (int i = 0; i < entries.length; i++) { if (entries[i].isDirectory()) { // generate directory entry ZipEntry zi = new ZipEntry(prefix + entries[i].getName() + "/"); try { zos.putNextEntry(zi); zos.closeEntry(); } catch (IOException ioex) { ioex.printStackTrace(); } zip(entries[i], zos, prefix + entries[i].getName() + "/"); } else { try { FileInputStream fis = new FileInputStream(entries[i]); ZipEntry zi = new ZipEntry(prefix + entries[i].getName()); zos.putNextEntry(zi); copystream(fis, zos); zos.closeEntry(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } } } return zos; } public static void copystream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >= 0) out.write(buffer, 0, len); in.close(); // out.close(); } }