Example usage for java.util.zip ZipInputStream read

List of usage examples for java.util.zip ZipInputStream read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:org.canova.api.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 * @param file the file to extract to/*from   w w  w  . jav  a 2 s .  c o m*/
 * @param dest the destination directory
 * @throws java.io.IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip")) {
        //getFromOrigin the zip file content
        ZipInputStream zis = new ZipInputStream(fin);
        //getFromOrigin the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();

            File newFile = new File(dest + File.separator + fileName);

            if (ze.isDirectory()) {
                newFile.mkdirs();
                zis.closeEntry();
                ze = zis.getNextEntry();
                continue;
            }

            log.info("file unzip : " + newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(data)) > 0) {
                fos.write(data, 0, len);
            }

            fos.flush();
            fos.close();
            zis.closeEntry();
            ze = zis.getNextEntry();
        }

        zis.close();

    }

    else if (file.endsWith(".tar")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();
                ;

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".gz")) {
        GZIPInputStream is2 = new GZIPInputStream(fin);
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        OutputStream fos = FileUtils.openOutputStream(extracted);
        IOUtils.copyLarge(is2, fos);
        is2.close();
        fos.flush();
        fos.close();
    }

}

From source file:org.jahia.test.utils.TestHelper.java

public static JahiaSite createSite(String name, String serverName, String templateSet, String prepackedZIPFile,
        String siteZIPName, String[] modulesToDeploy) throws Exception {
    modulesToDeploy = (modulesToDeploy == null) ? new String[0] : modulesToDeploy;

    JahiaUser admin = JahiaAdminUser.getAdminUser(null);

    JahiaSitesService service = ServicesRegistry.getInstance().getJahiaSitesService();
    JahiaSite site = service.getSiteByKey(name);

    if (site != null) {
        service.removeSite(site);//from   w  w  w. j  ava 2  s.  c  o  m
    }
    File siteZIPFile = null;
    File sharedZIPFile = null;
    try {
        if (!StringUtils.isEmpty(prepackedZIPFile)) {
            ZipInputStream zis = null;
            OutputStream os = null;
            try {
                zis = new ZipInputStream(new FileInputStream(new File(prepackedZIPFile)));
                ZipEntry z = null;
                while ((z = zis.getNextEntry()) != null) {
                    if (siteZIPName.equalsIgnoreCase(z.getName()) || "users.zip".equals(z.getName())) {
                        File zipFile = File.createTempFile("import", ".zip");
                        os = new FileOutputStream(zipFile);
                        byte[] buf = new byte[4096];
                        int r;
                        while ((r = zis.read(buf)) > 0) {
                            os.write(buf, 0, r);
                        }
                        os.close();
                        if ("users.zip".equals(z.getName())) {
                            sharedZIPFile = zipFile;
                        } else {
                            siteZIPFile = zipFile;
                        }
                    }
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                if (zis != null) {
                    try {
                        zis.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        }
        if (sharedZIPFile != null) {
            try {
                ImportExportBaseService.getInstance().importSiteZip(
                        sharedZIPFile != null ? new FileSystemResource(sharedZIPFile) : null, null, null);
            } catch (RepositoryException e) {
                logger.warn("shared.zip could not be imported", e);
            }
        }
        if (templateSet != null) {
            site = service.addSite(admin, name, serverName, name, name,
                    SettingsBean.getInstance().getDefaultLocale(), templateSet, modulesToDeploy,
                    siteZIPFile == null ? "noImport" : "fileImport",
                    siteZIPFile != null ? new FileSystemResource(siteZIPFile) : null, null, false, false, null);
        } else {
            site = addSiteWithoutTemplates(admin, name, serverName,
                    SettingsBean.getInstance().getDefaultLocale());
        }
        site = service.getSiteByKey(name);
    } finally {
        if (sharedZIPFile != null) {
            sharedZIPFile.delete();
        }
        if (siteZIPFile != null) {
            siteZIPFile.delete();
        }
    }

    return site;
}

From source file:com.oeg.oops.VocabUtils.java

/**
 * Code to unzip a file. Inspired from//from w w w.ja  va  2 s .  c om
 * http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/
 * Taken from
 * @param resourceName
 * @param outputFolder
 */
public static void unZipIt(String resourceName, String outputFolder) {

    byte[] buffer = new byte[1024];

    try {
        ZipInputStream zis = new ZipInputStream(VocabUtils.class.getResourceAsStream(resourceName));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            System.out.println("file unzip : " + newFile.getAbsoluteFile());
            if (ze.isDirectory()) {
                String temp = newFile.getAbsolutePath();
                new File(temp).mkdirs();
            } else {
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        System.err.println("Error while extracting the reosurces: " + ex.getMessage());
    }
}

From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java

/**
 * Un zip a file to a destination folder.
 * @param zipFile the zip file//from  ww w.jav a2s .c om
 * @param outputFolder the output folder
 */
public static void unZipFile(final String zipFile, final String outputFolder) {

    LogUtil.setLogString("UnZip the File", true);
    final byte[] buffer = new byte[1024];
    int len;
    try {
        // create output directory is not exists
        final File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }
        // get the zip file content
        final ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        final StringBuilder outFolderPath = new StringBuilder();
        final StringBuilder fileLogPath = new StringBuilder();
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
            final String fileName = zipEntry.getName();
            final File newFile = new File(
                    outFolderPath.append(outputFolder).append(File.separator).append(fileName).toString());
            LogUtil.setLogString(
                    fileLogPath.append("file unzip : ").append(newFile.getAbsoluteFile()).toString(), true);
            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
            final FileOutputStream fos = new FileOutputStream(newFile);

            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            fileLogPath.setLength(0);
            outFolderPath.setLength(0);
        }

        zis.closeEntry();
        zis.close();

        LogUtil.setLogString("Done", true);

    } catch (IOException ex) {
        LOGGER.error("Error in unzip file", ex);
    }
}

From source file:org.deegree.commons.utils.io.Zip.java

public static void unzip(final InputStream in, File dir, boolean overwrite)
        throws FileNotFoundException, IOException {
    ZipInputStream zin = new ZipInputStream(in);
    ZipEntry entry;//from   w  w  w  . j a  v  a2 s  . c om

    if (!dir.exists()) {
        dir.mkdir();
    }

    boolean rootRead = false;

    while ((entry = zin.getNextEntry()) != null) {
        if (entry.isDirectory()) {
            File f = new File(dir, entry.getName());
            // avoid directory-in-directory
            if (!rootRead) {
                if (f.getName().equals(dir.getName())) {
                    dir = dir.getParentFile();
                }
            }
            rootRead = true;
            f.mkdir();
            continue;
        }

        File f = new File(dir, entry.getName());

        if (f.exists() && !overwrite) {
            LOG.debug("Not overwriting {}.", f);
            continue;
        }

        byte[] bs = new byte[16384];
        File parent = f.getAbsoluteFile().getParentFile();
        parent.mkdirs();
        FileOutputStream out = new FileOutputStream(f);
        int read;
        while ((read = zin.read(bs)) != -1) {
            out.write(bs, 0, read);
        }
        out.close();
    }

    in.close();
}

From source file:net.minecraftforge.fml.common.asm.transformers.MarkerTransformer.java

private static void processJar(File inFile, File outFile, MarkerTransformer[] transformers) throws IOException {
    ZipInputStream inJar = null;
    ZipOutputStream outJar = null;

    try {//w w  w.  j av  a2 s.  c  om
        try {
            inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open input file: " + e.getMessage());
        }

        try {
            outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open output file: " + e.getMessage());
        }

        ZipEntry entry;
        while ((entry = inJar.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                outJar.putNextEntry(entry);
                continue;
            }

            byte[] data = new byte[4096];
            ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();

            int len;
            do {
                len = inJar.read(data);
                if (len > 0) {
                    entryBuffer.write(data, 0, len);
                }
            } while (len != -1);

            byte[] entryData = entryBuffer.toByteArray();

            String entryName = entry.getName();

            if (entryName.endsWith(".class") && !entryName.startsWith(".")) {
                ClassNode cls = new ClassNode();
                ClassReader rdr = new ClassReader(entryData);
                rdr.accept(cls, 0);
                String name = cls.name.replace('/', '.').replace('\\', '.');

                for (MarkerTransformer trans : transformers) {
                    entryData = trans.transform(name, name, entryData);
                }
            }

            ZipEntry newEntry = new ZipEntry(entryName);
            outJar.putNextEntry(newEntry);
            outJar.write(entryData);
        }
    } finally {
        IOUtils.closeQuietly(outJar);
        IOUtils.closeQuietly(inJar);
    }
}

From source file:org.jjdltc.cordova.plugin.zip.decompressZip.java

/**
 * Extracts a file//from ww  w.j a v a 2s .  co m
 * @param zipIn
 * @param filePath
 * @throws IOException
 */
private void extractFile(ZipInputStream zipFl, String filePath) throws IOException {
    BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(filePath));
    byte[] bytesIn = new byte[this.BUFFER_SIZE];
    int read = 0;
    while ((read = zipFl.read(bytesIn)) != -1) {
        buffer.write(bytesIn, 0, read);
    }
    buffer.close();
}

From source file:org.renjin.primitives.files.Files.java

/**
 * Helper function to extract a zip entry to the given folder.
 *//*from   w  ww . j  a v a2 s . co  m*/
private static void unzipExtract(ZipInputStream zin, ZipEntry entry, FileObject exdir, boolean junkpaths,
        boolean overwrite) throws IOException {
    if (junkpaths) {
        throw new EvalException("unzip(junpaths=false) not yet implemented");
    }

    FileObject exfile = exdir.resolveFile(entry.getName());
    if (exfile.exists() && !overwrite) {
        throw new EvalException("file to be extracted '%s' already exists", exfile.getName().getURI());
    }
    OutputStream out = exfile.getContent().getOutputStream();
    try {

        byte buffer[] = new byte[64 * 1024];
        int bytesRead;
        while ((bytesRead = zin.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    } finally {
        out.close();
    }
}

From source file:Main.java

private static File unzip(Context context, InputStream in) throws IOException {
    File tmpDb = null;/*from   w  w w  . j  a  v a 2  s  . c o  m*/
    int dbFiles = 0;
    try {
        tmpDb = File.createTempFile("import", ".db");

        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry sourceEntry;
        while (true) {

            sourceEntry = zin.getNextEntry();

            if (sourceEntry == null) {
                break;
            }

            if (sourceEntry.isDirectory()) {
                zin.closeEntry();
                continue;
            }

            FileOutputStream fOut;
            if (sourceEntry.getName().endsWith(".db")) {
                // Write database to tmp file
                fOut = new FileOutputStream(tmpDb);
                dbFiles++;
            } else {
                // Write all other files(images) to files dir in apps data
                int start = sourceEntry.getName().lastIndexOf("/") + 1;
                String name = sourceEntry.getName().substring(start);
                fOut = context.openFileOutput(name, Context.MODE_PRIVATE);
            }

            final OutputStream targetStream = fOut;
            try {
                int read;
                while (true) {
                    byte[] buffer = new byte[1024];
                    read = zin.read(buffer);
                    if (read == -1) {
                        break;
                    }
                    targetStream.write(buffer, 0, read);
                }
                targetStream.flush();
            } finally {
                safeCloseClosable(targetStream);
            }
            zin.closeEntry();
        }
    } finally {
        safeCloseClosable(in);
    }
    if (dbFiles != 1) {
        throw new IllegalStateException("Input file is not a valid backup");
    }
    return tmpDb;
}

From source file:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Extracts a zip entry (file entry)//  w  w w. j  ava2s  .com
 *
 * @param zipIn
 * @param filePath
 * @throws IOException
 */
protected static void extractFile(GenerationLogger GENERATION_LOGGER, ZipInputStream zipIn, String filePath)
        throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
    byte[] bytesIn = new byte[4096];
    int read = 0;
    while ((read = zipIn.read(bytesIn)) != -1) {
        bos.write(bytesIn, 0, read);
    }
    bos.close();
    GENERATION_LOGGER.debug("Extracted zip Entry: " + filePath);
}