将给定文件添加到给定zip文件中。
//package com.nowjava; import java.io.BufferedInputStream; /* 时代Java公众号 */ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /* 时 代 J a v a 提 供 */ public static void addToZip(File zipFile, File source, String pathInZip) throws IOException { addToZip(zipFile, new File[] { source }, pathInZip); } /** * Adds the given file to the given zip file. * @param zipFile the zip file to add to * @param files file to add */ public static void addToZip(File zipFile, File[] files, String pathInZip) throws IOException { FileOutputStream fOut = null; ZipOutputStream zipOut = null; try { fOut = new FileOutputStream(zipFile); zipOut = new ZipOutputStream(fOut); for (File f : files) { addToZip(zipOut, f, pathInZip); } } finally { if (zipOut != null) zipOut.close(); else if (fOut != null) fOut.close(); } } private static void addToZip(ZipOutputStream zipOut, File source, String pathInZip) throws IOException { BufferedOutputStream out = null; FileInputStream fIn = null; BufferedInputStream in = null; final int bufSize = 512; try { // Open our streams fIn = new FileInputStream(source); in = new BufferedInputStream(fIn, bufSize); String filePathInZip = pathInZip + "/" + source.getName(); if (pathInZip.equals("")) filePathInZip = source.getName(); // System.out.println("Adding " + filePathInZip); ZipEntry entry = new ZipEntry(filePathInZip); zipOut.putNextEntry(entry); out = new BufferedOutputStream(zipOut, bufSize); int count = 0; byte[] buffer = new byte[bufSize]; while ((count = in.read(buffer, 0, buffer.length)) > -1) { out.write(buffer, 0, count);