Java Zip Files addFileToZip(File in, File parent, ZipOutputStream out)

Here you can find the source of addFileToZip(File in, File parent, ZipOutputStream out)

Description

read a file out to the zip stream

License

Open Source License

Declaration

protected static void addFileToZip(File in, File parent, ZipOutputStream out) throws IOException 

Method Source Code


//package com.java2s;
/* *******************************************************************
 * Copyright (c) 1999-2000 Xerox Corporation. 
 * All rights reserved. /*w  w  w.  j av  a2 s  .co  m*/
 * This program and the accompanying materials are made available 
 * under the terms of the Eclipse Public License v1.0 
 * which accompanies this distribution and is available at 
 * http://www.eclipse.org/legal/epl-v10.html 
 *  
 * Contributors: 
 *     Xerox/PARC     initial implementation 
 * ******************************************************************/

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Main {
    /** read a file out to the zip stream */
    protected static void addFileToZip(File in, File parent, ZipOutputStream out) throws IOException {
        String path = in.getCanonicalPath();
        String parentPath = parent.getCanonicalPath();
        if (!path.startsWith(parentPath)) {
            throw new Error("not parent: " + parentPath + " of " + path);
        } else {
            path = path.substring(1 + parentPath.length());
            path = path.replace('\\', '/'); // todo: use filesep
        }
        ZipEntry entry = new ZipEntry(path);
        entry.setTime(in.lastModified());
        // todo: default behavior is DEFLATED

        out.putNextEntry(entry);

        InputStream input = null;
        try {
            input = new FileInputStream(in);
            byte[] buf = new byte[1024];
            int count;
            while (0 < (count = input.read(buf, 0, buf.length))) {
                out.write(buf, 0, count);
            }
        } finally {
            if (null != input)
                input.close();
        }
    }
}

Related

  1. addFilesToZip(File zipFile, File[] files, String[] fileNames)
  2. addFileToZip(File file, String entryName, ZipOutputStream zos)
  3. addFileToZip(File file, String entryName, ZipOutputStream zOut)
  4. addFileToZip(File file, String parentFolderName, ZipOutputStream zip)
  5. addFileToZip(File file, ZipOutputStream zos)
  6. addFileToZip(File root, File file, ZipOutputStream zos)
  7. addFileToZip(final File file, final String zipName, final ZipOutputStream zipout)
  8. addFileToZip(final String path, final String srcFile, final ZipOutputStream zip, boolean flag)
  9. addFileToZip(final String pathInsideZip, final File fileToZip, final ZipOutputStream outZip)