Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:com.nkapps.billing.services.BankStatementServiceImpl.java

@Override
public File extractedFile(File file) throws Exception {
    File extractedFile = null;/*ww w  . j a  v  a 2 s.c  o m*/

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        String extFileName = ze.getName();
        extractedFile = new File(getUploadDir() + File.separator + extFileName);
        if (!extractedFile.exists()) {
            extractedFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(extractedFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();

    return extractedFile;
}

From source file:com.oprisnik.semdroid.Semdroid.java

protected void extract(InputStream source, File targetDir) {
    if (!targetDir.exists()) {
        targetDir.mkdirs();//from   w  w  w  .j a va  2 s .c om
    }
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "Extracting to " + targetDir);
    }

    try {
        ZipInputStream zip = new ZipInputStream(source);
        ZipEntry entry = null;

        while ((entry = zip.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                File dir = new File(targetDir, entry.getName());
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            } else {
                File newFile = new File(targetDir, entry.getName());
                FileOutputStream fout = new FileOutputStream(newFile);
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Extracting " + entry.getName() + " to " + newFile);
                }

                byte[] data = new byte[BUFFER];
                int count;
                while ((count = zip.read(data, 0, BUFFER)) != -1) {
                    fout.write(data, 0, count);
                }
                zip.closeEntry();
                fout.close();
            }

        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        IOUtils.closeQuietly(source);
    }
}

From source file:org.kurator.validation.actors.io.DwCaReader.java

@Override
public void fireOnce() throws Exception {
    File file = new File(filePath);
    if (!file.exists()) {
        // Error//from ww w. j a  v  a  2  s  .c  o  m
        logger.error(filePath + " not found.");
    }
    if (!file.canRead()) {
        // error
        logger.error("Unable to read " + filePath);
    }
    if (file.isDirectory()) {
        // check if it is an unzipped dwc archive.
        dwcArchive = openArchive(file);
    }
    if (file.isFile()) {
        // unzip it
        File outputDirectory = new File(file.getName().replace(".", "_") + "_content");
        if (!outputDirectory.exists()) {
            outputDirectory.mkdir();
            try {
                byte[] buffer = new byte[1024];
                ZipInputStream inzip = new ZipInputStream(new FileInputStream(file));
                ZipEntry entry = inzip.getNextEntry();
                while (entry != null) {
                    String fileName = entry.getName();
                    File expandedFile = new File(outputDirectory.getPath() + File.separator + fileName);
                    new File(expandedFile.getParent()).mkdirs();
                    FileOutputStream expandedfileOutputStream = new FileOutputStream(expandedFile);
                    int len;
                    while ((len = inzip.read(buffer)) > 0) {
                        expandedfileOutputStream.write(buffer, 0, len);
                    }

                    expandedfileOutputStream.close();
                    entry = inzip.getNextEntry();
                }
                inzip.closeEntry();
                inzip.close();
                System.out.println("Unzipped archive into " + outputDirectory.getPath());
            } catch (FileNotFoundException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                logger.error(e.getMessage());
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // look into the unzipped directory
        dwcArchive = openArchive(outputDirectory);

        iterator = dwcArchive.iterator();
        while (iterator.hasNext()) {
            // read initial set of rows, pass downstream
            StarRecord dwcrecord = iterator.next();
            SpecimenRecord record = new SpecimenRecord(dwcrecord);
            broadcast(record);
        }
    }
    if (dwcArchive != null) {
        if (checkArchive()) {
            // good to go
        }
    } else {
        System.out.println("Problem opening archive.");
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * 2jar?,??jar/* w ww .  j  a v a2  s .co m*/
 * @param baseJar
 * @param diffJar
 * @param outJar
 */
public static void unionJar(File baseJar, File diffJar, File outJar) throws IOException {
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    List<String> diffEntries = getZipEntries(diffJar);
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(baseJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (diffEntries.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();

}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

public static void splitZip(File inputFile, File outputFile, Set<String> includeEnties) throws IOException {
    if (outputFile.exists()) {
        FileUtils.deleteQuietly(outputFile);
    }//w  w  w.  j  a va 2 s  . c  o  m
    if (null == includeEnties || includeEnties.size() < 1) {
        return;
    }
    FileOutputStream fos = new FileOutputStream(outputFile);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inputFile);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (!includeEnties.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
}

From source file:sernet.verinice.service.sync.VeriniceArchive.java

/**
 * Extracts all entries of a Zip-Archive
 * /*from w  w  w .  j  a va2 s . c om*/
 * @param zipFileData Data of a zip archive
 * @throws IOException
 */
public void extractZipEntries(byte[] zipFileData) throws IOException {
    byte[] buffer = new byte[1024];
    ;
    new File(getTempDirName()).mkdirs();
    // get the zip file content
    ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipFileData));
    // get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        if (!ze.isDirectory()) {
            String fileName = ze.getName();
            File newFile = new File(getTempDirName() + File.separator + fileName);
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

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

            fos.close();

            if (LOG.isDebugEnabled()) {
                LOG.debug("File unzipped: " + newFile.getAbsoluteFile());
            }
        }
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.file.shape.LocalShapeReader.java

private void unzipShapefiles(File shapefileCompressedData) throws IOException {
    IOException error = null;//from  w  w w .j a va2  s.co m
    if (!shapefilesFolder.exists()) {
        shapefilesFolder.mkdirs();
    }
    InputStream bis = new FileInputStream(shapefileCompressedData);
    ZipInputStream zis = new ZipInputStream(bis);
    ZipEntry ze;
    try {
        while ((ze = zis.getNextEntry()) != null) {
            if (!ze.isDirectory()) {
                String fileName = ze.getName();
                File unzippedFile = new File(shapefilesFolder, fileName);
                byte[] buffer = new byte[1024];
                FileOutputStream fos = new FileOutputStream(unzippedFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                if (fileName.toLowerCase().endsWith(".shp")) {
                    shapefilePath = unzippedFile.toURI();
                }
            }
        }
    } catch (IOException e) {
        error = e;
    } finally {
        try {
            zis.closeEntry();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            zis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (error != null) {
        throw error;
    }
}

From source file:com.seer.datacruncher.services.ftp.FTPPollJobProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    String result = "";
    GenericFile file = (GenericFile) exchange.getIn().getBody();
    Message message = exchange.getOut();
    String inputFileName = file.getFileName();
    Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
    if (isValidFileName(inputFileName)) {
        long schemaId = getSchemaIdUsingFileName(inputFileName);
        long userId = getUserIdFromFileName(inputFileName);
        if (!usersDao.isUserAssoicatedWithSchema(userId, schemaId)) {
            result = "User not authorized";
        } else {//from w  ww . j  a  va 2s.  co  m
            resultMap.put(inputFileName, file.getBody().toString().getBytes());
            SchemaEntity schemaEntity = schemasDao.find(schemaId);
            if (schemaEntity == null) {
                result = "No schema found in database with Id [" + schemaId + "]";
            } else {
                if (inputFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) {
                    // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one   
                    ZipInputStream inStream = null;
                    try {
                        inStream = new ZipInputStream(new ByteArrayInputStream(resultMap.get(inputFileName)));
                        ZipEntry entry;
                        while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                            if (!entry.isDirectory()) {
                                DatastreamsInput datastreamsInput = new DatastreamsInput();
                                datastreamsInput.setUploadedFileName(entry.getName());
                                byte[] byteInput = IOUtils.toByteArray(inStream);
                                result += datastreamsInput.datastreamsInput(new String(byteInput), schemaId,
                                        byteInput);
                            }
                            inStream.closeEntry();
                        }
                    } catch (IOException ex) {
                        result = "Error occured during fetch records from ZIP file.";
                    } finally {
                        if (inStream != null)
                            inStream.close();
                    }
                } else {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(inputFileName);
                    result = datastreamsInput.datastreamsInput(new String(resultMap.get(inputFileName)),
                            schemaId, resultMap.get(inputFileName));
                }
            }
        }
    } else {
        result = "File Name not in specified format.";
    }

    // Store in Ftp location
    CamelContext context = exchange.getContext();
    FtpComponent component = context.getComponent("ftp", FtpComponent.class);
    FtpEndpoint<?> endpoint = (FtpEndpoint<?>) component.createEndpoint(getFTPEndPoint());

    Exchange outExchange = endpoint.createExchange();
    outExchange.getIn().setBody(result);
    outExchange.getIn().setHeader("CamelFileName", getFileNameWithoutExtensions(inputFileName) + ".txt");
    Producer producer = endpoint.createProducer();
    producer.start();
    producer.process(outExchange);
    producer.stop();
}

From source file:com.gatf.executor.report.ReportHandler.java

/**
  * @param zipFile// w ww. j  a  v a2 s  .  com
  * @param directoryToExtractTo Provides file unzip functionality
  */
public static void unzipZipFile(InputStream zipFile, String directoryToExtractTo) {
    ZipInputStream in = new ZipInputStream(zipFile);
    try {
        File directory = new File(directoryToExtractTo);
        if (!directory.exists()) {
            directory.mkdirs();
            logger.info("Creating directory for Extraction...");
        }
        ZipEntry entry = in.getNextEntry();
        while (entry != null) {
            try {
                File file = new File(directory, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    FileOutputStream out = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    out.close();
                }
                in.closeEntry();
                entry = in.getNextEntry();
            } catch (Exception e) {
                logger.severe(ExceptionUtils.getStackTrace(e));
            }
        }
    } catch (IOException ioe) {
        logger.severe(ExceptionUtils.getStackTrace(ioe));
        return;
    }
}

From source file:org.wisdom.monitor.extensions.jcr.backup.ModeshapeJcrBackupExtension.java

public void unzip(File fileToUnzip, File folderToUnzipInto) {

    byte[] buffer = new byte[1024];

    try {//w ww  .j a v a 2  s  .co  m
        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(fileToUnzip));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }

            String fileName = ze.getName();
            File newFile = new File(folderToUnzipInto + File.separator + fileName);

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            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) {
        ex.printStackTrace();
    }
}