Here you can find the source of zipFolder(String sourceFolder, String target)
Parameter | Description |
---|---|
sourceFolder | a parameter |
target | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static void zipFolder(String sourceFolder, String target) throws IOException
//package com.java2s; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**/*from ww w . j a v a 2 s . c o m*/ * @param sourceFolder * @param target * @throws IOException */ public static void zipFolder(String sourceFolder, String target) throws IOException { List<String> fileList = generateFileList(sourceFolder, new File(sourceFolder)); byte[] buffer = new byte[1024]; FileOutputStream fos = null; ZipOutputStream zos = null; try { fos = new FileOutputStream(target); zos = new ZipOutputStream(fos); FileInputStream in = null; for (String file : fileList) { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); try { in = new FileInputStream(sourceFolder + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } } finally { in.close(); } } zos.closeEntry(); } catch (IOException ex) { throw ex; } finally { try { zos.close(); } catch (IOException e) { throw e; } } } /** * @param node */ private static List<String> generateFileList(String sourceFolder, File node) { List<String> fileList = new ArrayList<String>(); // add file only if (node.isFile()) { fileList.add(generateZipEntry(sourceFolder, node.toString())); } if (node.isDirectory()) { String[] subNote = node.list(); for (String filename : subNote) { fileList.addAll(generateFileList(sourceFolder, new File(node, filename))); } } return fileList; } private static String generateZipEntry(String sourceFolder, String file) { return file.substring(sourceFolder.length() + 1, file.length()); } }