Here you can find the source of addToZip(File directoryToZip, File file, ZipOutputStream zos)
Parameter | Description |
---|---|
directoryToZip | - zip file |
file | - a file to add |
zos | - ZipOutputStream |
Parameter | Description |
---|---|
FileNotFoundException | an exception |
IOException | an exception |
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException, IOException
//package com.java2s; /******************************************************************************* * Copyright (c) 2015 CA. All rights reserved. * * This source file is licensed under the terms of the Eclipse Public License 1.0 * For the full text of the EPL please see https://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { /**//from w w w .j av a 2s. c o m * Add a file to the zip file * * @param directoryToZip - zip file * @param file - a file to add * @param zos - ZipOutputStream * @throws FileNotFoundException * @throws IOException */ public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException, IOException { FileInputStream fis = null; try { fis = new FileInputStream(file); // we want the zipEntry's path to be a relative path that is relative // to the directory being zipped, so chop off the rest of the path String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1, file.getCanonicalPath().length()); System.out.println("Writing '" + zipFilePath + "' to zip file"); ZipEntry zipEntry = new ZipEntry(zipFilePath); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } } finally { safeZipOutputStreamcloseEntry(zos); safeFileInputStreamClose(fis); } } /** * Closes the current ZIP entry and positions the stream for writing the next entry * * @param zos - an output stream filter for writing files in the ZIP file format */ public static void safeZipOutputStreamcloseEntry(ZipOutputStream zos) { if (zos != null) { try { zos.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } /** * Closes the file input stream and releases any system resources associated with the stream. * * @param fis - reading streams of raw bytes */ public static void safeFileInputStreamClose(FileInputStream fis) { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }