Here you can find the source of zipFile(final File source)
Parameter | Description |
---|---|
source | The file to archive. |
Parameter | Description |
---|---|
IOException | if problems were experienced. |
public static void zipFile(final File source) throws IOException
//package com.java2s; /*/*from w w w. ja v a 2s . c o m*/ * Copyright (c) 2003 Stephan D. Cote' - All rights reserved. * * This program and the accompanying materials are made available under the * terms of the MIT License which accompanies this distribution, and is * available at http://creativecommons.org/licenses/MIT/ * * Contributors: * Stephan D. Cote * - Initial API and implementation */ import java.io.BufferedInputStream; 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 { private static final int STREAM_BUFFER_SIZE = 8 * 1024; private static final String ZIP_SUFFIX = ".zip"; /** * Zip a single file into a compressed ZIP archive. * * <p>This will result in a compressed archive that contain a single file * entry. The name of the archive will be the name of the source file with * the added extension of 'zip'. * * @param source The file to archive. * * @throws IOException if problems were experienced. */ public static void zipFile(final File source) throws IOException { zipFile(source, new File(source.getAbsolutePath() + ZIP_SUFFIX)); } /** * Zip a single file into a compressed ZIP archive. * * <p>This will result in a compressed archive that contain a single file * entry. The name of the archive will be the name of the source file with * the added extension of 'zip'. * * @param source The file to archive. * @param target the archive file to write * * @throws IOException if problems were experienced. */ public static void zipFile(final File source, final File target) throws IOException { BufferedInputStream origin = null; ZipOutputStream out = null; try { final FileOutputStream dest = new FileOutputStream(target); out = new ZipOutputStream(new BufferedOutputStream(dest)); final byte data[] = new byte[STREAM_BUFFER_SIZE]; final FileInputStream fi = new FileInputStream(source); origin = new BufferedInputStream(fi, STREAM_BUFFER_SIZE); final ZipEntry entry = new ZipEntry(source.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, STREAM_BUFFER_SIZE)) != -1) { out.write(data, 0, count); } } catch (final FileNotFoundException e) { throw new IOException(e.getMessage()); } finally { try { if (origin != null) { origin.close(); } } catch (final IOException ignore) { } try { if (out != null) { out.close(); } } catch (final IOException ignore) { } } } }