Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

In this page you can find the example usage for java.util.zip ZipEntry ZipEntry.

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:Main.java

/**
 * zips a directory//from   www  .j  ava2 s . c o  m
 * @param dir2zip
 * @param zipOut
 * @param zipFileName
 * @throws IOException
 */
private static void zipDir(String dir2zip, ZipOutputStream zipOut, String zipFileName) throws IOException {
    File zipDir = new File(dir2zip);
    // get a listing of the directory content
    String[] dirList = zipDir.list();
    byte[] readBuffer = new byte[2156];
    int bytesIn = 0;
    // loop through dirList, and zip the files
    for (int i = 0; i < dirList.length; i++) {
        File f = new File(zipDir, dirList[i]);
        if (f.isDirectory()) {
            // if the File object is a directory, call this
            // function again to add its content recursively
            String filePath = f.getPath();
            zipDir(filePath, zipOut, zipFileName);
            // loop again
            continue;
        }

        if (f.getName().equals(zipFileName)) {
            continue;
        }
        // if we reached here, the File object f was not a directory
        // create a FileInputStream on top of f
        final InputStream fis = new BufferedInputStream(new FileInputStream(f));
        try {
            ZipEntry anEntry = new ZipEntry(f.getPath().substring(dir2zip.length() + 1));
            // place the zip entry in the ZipOutputStream object
            zipOut.putNextEntry(anEntry);
            // now write the content of the file to the ZipOutputStream
            while ((bytesIn = fis.read(readBuffer)) != -1) {
                zipOut.write(readBuffer, 0, bytesIn);
            }
        } finally {
            // close the Stream
            fis.close();
        }
    }
}

From source file:net.grinder.util.LogCompressUtil.java

/**
 * Compress multiple Files./*  w w  w .  ja  v  a 2  s  . c o  m*/
 * 
 * @param logFiles
 *            files to be compressed
 * @return compressed file byte array
 */
public static byte[] compressFile(File[] logFiles) {
    FileInputStream fio = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    try {

        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        for (File each : logFiles) {
            try {
                fio = new FileInputStream(each);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[COMPRESS_BUFFER_SIZE];
                int count = 0;
                while ((count = fio.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    zos.write(buffer, 0, count);
                }
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compress {}", each.getAbsolutePath());
                LOGGER.error("Details", e);
            } finally {
                IOUtils.closeQuietly(fio);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.info("Error occurs while compress log : {} ", e.getMessage());
        LOGGER.debug("Details", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(fio);
        IOUtils.closeQuietly(out);
    }
}

From source file:jodtemplate.io.ZipWriter.java

public void zipResources(final Resources resources, final OutputStream output) throws IOException {
    try (final ZipOutputStream zos = new ZipOutputStream(output);
            final BufferedOutputStream bos = new BufferedOutputStream(zos)) {
        for (Resource resource : resources.getResources()) {
            zos.putNextEntry(new ZipEntry(resource.getName()));
            try (final InputStream is = resource.getInputStream()) {
                zos.write(IOUtils.toByteArray(is));
            }/*from   ww  w. java2  s  .c  o  m*/
            zos.closeEntry();
        }
    }
}

From source file:com.digitalreasoning.herman.JarCreater.java

public static void createJar(File outputJarFile, List<Entry> entries) throws IOException {
    if (!outputJarFile.getParentFile().exists()) {
        outputJarFile.getParentFile().mkdirs();
    }/* w  w  w  .java  2s  .co m*/
    if (!outputJarFile.exists()) {
        outputJarFile.createNewFile();
    }

    FileOutputStream fOut = new FileOutputStream(outputJarFile);
    JarOutputStream jarOut = new JarOutputStream(fOut);
    Set<String> packageSet = new HashSet<String>();
    try {
        for (Entry folderFile : entries) {
            InputStream inputStream = folderFile.resource.openStream();

            try {
                if (!packageSet.contains(folderFile.parentFolderName)) {
                    jarOut.putNextEntry(new ZipEntry(folderFile.parentFolderName));
                    jarOut.closeEntry();
                    packageSet.add(folderFile.parentFolderName);
                }

                jarOut.putNextEntry(new ZipEntry(folderFile.parentFolderName
                        + (folderFile.parentFolderName.endsWith("/") ? "" : "/") + folderFile.fileName));
                IOUtils.copy(inputStream, jarOut);
                jarOut.closeEntry();
            } finally {
                inputStream.close();
            }

        }

    } finally {
        jarOut.close();
        fOut.close();
    }
}

From source file:com.autentia.web.rest.wadl.zipper.Zip.java

public void add(String name, InputStream inputStream) throws IOException {
    zipOutputStream.putNextEntry(new ZipEntry(name));

    IOUtils.copy(inputStream, zipOutputStream);

    zipOutputStream.closeEntry();/* w  ww . j  ava 2 s  .  c  o m*/
}

From source file:com.google.refine.model.medadata.PackageExtension.java

/**
 * Do the package since the final spec for the compression/bundle are not settled yet.
 * https://github.com/frictionlessdata/datapackage-js/issues/93
 * //from  w  w  w. j  a v  a 2 s. c  o m
 * @param pkg Package 
 * @param dataByteArrayOutputStream  ByteArrayOutputStream
 * @param destOs OutputStream
 * @throws IOException 
 * @throws FileNotFoundException 
 * @see Package#saveZip(String outputFilePath) 
 */
public static void saveZip(Package pkg, final ByteArrayOutputStream dataByteArrayOutputStream,
        final OutputStream destOs) throws FileNotFoundException, IOException {
    try (ZipOutputStream zos = new ZipOutputStream(destOs)) {
        // json file 
        ZipEntry entry = new ZipEntry(DataPackageMetadata.DEFAULT_FILE_NAME);
        zos.putNextEntry(entry);
        zos.write(pkg.getJson().toString(JSON_INDENT_FACTOR).getBytes());
        zos.closeEntry();
        // default data file to data.csv or given path(can only handle one file because files cannot be restored)
        String path = (String) pkg.getResources().get(0).getPath();
        entry = new ZipEntry(StringUtils.isBlank(path) ? "data.csv" : path);
        zos.putNextEntry(entry);
        zos.write(dataByteArrayOutputStream.toByteArray());
        zos.closeEntry();
    }
}

From source file:Main.java

/**
 * Zips a file at a location and places the resulting zip file at the toLocation.
 * <p/>//from ww w.  ja v  a2s  .co  m
 * Example:
 * zipFileAtPath("downloads/myfolder", "downloads/myFolder.zip");
 * <p/>
 * http://stackoverflow.com/a/14868161
 */
public static void zipFileAtPath(String sourcePath, String toLocation) throws IOException {
    final int BUFFER = 2048;

    File sourceFile = new File(sourcePath);
    FileOutputStream fos = new FileOutputStream(toLocation);
    ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(fos));

    if (sourceFile.isDirectory()) {
        zipSubFolder(zipOut, sourceFile, sourceFile.getParent().length() + 1); // ??

    } else {
        byte data[] = new byte[BUFFER];
        FileInputStream fis = new FileInputStream(sourcePath);
        BufferedInputStream bis = new BufferedInputStream(fis, BUFFER);

        String lastPathComponent = sourcePath.substring(sourcePath.lastIndexOf("/"));

        ZipEntry zipEntry = new ZipEntry(lastPathComponent);
        zipOut.putNextEntry(zipEntry);

        int count;
        while ((count = bis.read(data, 0, BUFFER)) != -1) {
            zipOut.write(data, 0, count);
        }
    }

    zipOut.close();
}

From source file:Main.java

/**
 * Compress files to a zip/*  w w  w .j  ava 2 s .com*/
 * @param zip
 * @param files
 * @throws IOException 
 */
public static void compressToZip(File zip, File[] files) throws IOException {
    byte data[] = new byte[BUFFER];
    FileOutputStream fozip = new FileOutputStream(zip);
    ZipOutputStream zo = new ZipOutputStream(new BufferedOutputStream(fozip));
    for (int i = 0; i < files.length; i++) {
        System.out.println("Adding:" + files[i]);
        FileInputStream fi = new FileInputStream(files[i]);
        BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
        ZipEntry zipentry = new ZipEntry(files[i].getName());
        zo.putNextEntry(zipentry);
        int count;
        while ((count = origin.read(data, 0, BUFFER)) != -1) {
            zo.write(data, 0, count);
        }
        origin.close();
    }
    zo.close();
}

From source file:brut.directory.ZipUtils.java

private static void processFolder(final File folder, final ZipOutputStream zipOutputStream,
        final int prefixLength) throws BrutException, IOException {
    for (final File file : folder.listFiles()) {
        if (file.isFile()) {
            final String cleanedPath = BrutIO.sanitizeUnknownFile(folder,
                    file.getPath().substring(prefixLength));
            final ZipEntry zipEntry = new ZipEntry(BrutIO.normalizePath(cleanedPath));

            // aapt binary by default takes in parameters via -0 arsc to list extensions that shouldn't be
            // compressed. We will replicate that behavior
            final String extension = FilenameUtils.getExtension(file.getAbsolutePath());
            if (mDoNotCompress != null
                    && (mDoNotCompress.contains(extension) || mDoNotCompress.contains(zipEntry.getName()))) {
                zipEntry.setMethod(ZipEntry.STORED);
                zipEntry.setSize(file.length());
                BufferedInputStream unknownFile = new BufferedInputStream(new FileInputStream(file));
                CRC32 crc = BrutIO.calculateCrc(unknownFile);
                zipEntry.setCrc(crc.getValue());
                unknownFile.close();/*from w ww.  jav a  2  s  .  co m*/
            } else {
                zipEntry.setMethod(ZipEntry.DEFLATED);
            }

            zipOutputStream.putNextEntry(zipEntry);
            try (FileInputStream inputStream = new FileInputStream(file)) {
                IOUtils.copy(inputStream, zipOutputStream);
            }
            zipOutputStream.closeEntry();
        } else if (file.isDirectory()) {
            processFolder(file, zipOutputStream, prefixLength);
        }
    }
}

From source file:com.nuvolect.securesuite.util.OmniZip.java

public static boolean zipFiles(Context ctx, Iterable<OmniFile> files, OmniFile zipOmni, int destination) {

    ZipOutputStream zos = null;//  w ww.j av  a2s.  com
    LogUtil.log(LogUtil.LogType.OMNI_ZIP, "ZIPPING TO: " + zipOmni.getPath());

    try {
        zos = new ZipOutputStream(zipOmni.getOutputStream());

        for (OmniFile file : files) {

            if (file.isDirectory()) {

                zipSubDirectory(ctx, "", file, zos);
            } else {

                LogUtil.log(LogUtil.LogType.OMNI_ZIP,
                        "zipping up: " + file.getPath() + " (bytes: " + file.length() + ")");

                /**
                 * Might get lucky here, can it associate the name with the copyLarge that follows
                 */
                ZipEntry ze = new ZipEntry(file.getName());
                zos.putNextEntry(ze);

                IOUtils.copyLarge(file.getFileInputStream(), zos);

                zos.flush();
            }
        }

        zos.close();
        return true;
    } catch (IOException e) {
        LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e);
        e.printStackTrace();
    }

    return false;
}