Example usage for java.util.zip ZipInputStream getNextEntry

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

Introduction

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

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:hu.sztaki.lpds.pgportal.services.dspace.DSpaceUtil.java

/**
 * Extracts any file from <code>inputFile</code> that begins with
 * 'bitstream' to <code>outputFile</code>.
 * Adapted from examples on//  w  ww.  j a v a  2 s .c  o  m
 * http://java.sun.com/developer/technicalArticles/Programming/compression/
 *
 * @param inputFile  File to extract 'bitstream...' from
 * @param outputFile  File to extract 'bitstream...' to
 */
private static void unzipBitstream(InputStream is, File outputFile) throws IOException {
    final int BUFFER = 2048;
    BufferedOutputStream dest = null;
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    try {

        while ((entry = zis.getNextEntry()) != null) {
            if (entry.getName().matches("bitstream.*")) {
                int count;
                byte data[] = new byte[BUFFER];

                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(outputFile.getAbsoluteFile());
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                    //System.out.println("Writing: " + outputFile.getAbsoluteFile());
                }
                dest.flush();
                dest.close();
            }
        }
    } finally {
        zis.close();
        try {
            dest.close();
        } catch (Exception e) {
        }
    }
}

From source file:de.ingrid.importer.udk.util.Zipper.java

/**
 * Extracts the given ZIP-File and return a vector containing String
 * representation of the extracted files.
 * //from  ww  w.ja v a 2  s  . c o  m
 * @param zipFileName
 *            the name of the ZIP-file
 * @param targetDir
 *            the target directory
 * @param keepSubfolders
 *            boolean parameter, whether to keep the folder structure
 * 
 * @return a Vector<String> containing String representation of the allowed
 *         files from the ZipperFilter.
 * @return null if the input data was invalid or an Exception occurs
 */
public static final List<String> extractZipFile(InputStream myInputStream, final String targetDir,
        final boolean keepSubfolders, ZipperFilter zipperFilter) {
    if (log.isDebugEnabled()) {
        log.debug("extractZipFile: inputStream=" + myInputStream + ", targetDir='" + targetDir
                + "', keepSubfolders=" + keepSubfolders);
    }

    ArrayList<String> extractedFiles = new ArrayList<String>();

    FileOutputStream fos = null;

    File outdir = new File(targetDir);

    // make some checks
    if (outdir.isFile()) {
        String msg = "The Target Directory \"" + outdir + "\" must not be a file .";
        log.error(msg);
        System.err.println(msg);
        return null;
    }

    // create necessary directories for the output directory
    outdir.mkdirs();

    // Start Unzipping ...
    try {
        if (log.isDebugEnabled()) {
            log.debug("Start unzipping");
        }

        ZipInputStream zis = new ZipInputStream(myInputStream);
        if (log.isDebugEnabled()) {
            log.debug("ZipInputStream from InputStream=" + zis);
        }

        // for every zip-entry
        ZipEntry zEntry;
        String name;
        while ((zEntry = zis.getNextEntry()) != null) {
            name = zEntry.toString();
            if (log.isDebugEnabled()) {
                log.debug("Zip Entry name: " + name + ", size:" + zEntry.getSize());
            }

            boolean isDir = name.endsWith(separator);
            // System.out.println("------------------------------");
            // System.out.println((isDir? "<d>":"< >")+name);

            String[] nameSplitted = name.split(separator);

            // If it's a File, take all Splitted Names except the last one
            int len = (isDir ? nameSplitted.length : nameSplitted.length - 1);

            String currStr = targetDir;

            if (keepSubfolders) {

                // create all directories from the entry
                for (int j = 0; j < len; j++) {
                    // System.out.println("Dirs: " + nameSplitted[j]);
                    currStr += nameSplitted[j] + File.separator;
                    // System.out.println("currStr: "+currStr);

                    File currDir = new File(currStr);
                    currDir.mkdirs();

                }
            }

            // if the entry is a file, then create it.
            if (!isDir) {

                // set the file name of the output file.
                String outputFileName = null;
                if (keepSubfolders) {
                    outputFileName = currStr + nameSplitted[nameSplitted.length - 1];
                } else {
                    outputFileName = targetDir + nameSplitted[nameSplitted.length - 1];
                }

                File outputFile = new File(outputFileName);
                fos = new FileOutputStream(outputFile);

                // write the File
                if (log.isDebugEnabled()) {
                    log.debug("Write Zip Entry '" + name + "' to file '" + outputFile + "'");
                }
                writeFile(zis, fos, buffersize);
                if (log.isDebugEnabled()) {
                    log.debug("FILE WRITTEN: " + outputFile.getAbsolutePath());
                }

                // add the file to the vector to be returned

                if (zipperFilter != null) {
                    String[] accFiles = zipperFilter.getAcceptedFiles();
                    String currFileName = outputFile.getAbsolutePath();

                    for (int i = 0; i < accFiles.length; i++) {
                        if (currFileName.endsWith(accFiles[i])) {
                            extractedFiles.add(currFileName);
                        }
                    }

                } else {
                    extractedFiles.add(outputFile.getAbsolutePath());
                }

            }

        } // end while

        zis.close();

    } catch (Exception e) {
        log.error("Problems unzipping file", e);
        e.printStackTrace();
        return null;
    }

    return extractedFiles;
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param stream zip input stream//from w ww.j a v a  2s.c om
 * @param dir directory to unzip
 * @param unique if need add unique suffix to every file name then true
 * @throws java.io.IOException
 * @return list of unzipped file names
 */
public static List<String> unZIP(InputStream stream, File dir, boolean unique) throws IOException {
    Long createdTime = new Date().getTime();
    String randomName = SecurityHelper.generateRandomSequence(16);
    List<String> fileNames = new ArrayList<String>();
    ZipInputStream in = new ZipInputStream(stream);
    ZipEntry entry;
    while ((entry = in.getNextEntry()) != null) {
        String name = entry.getName();
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(new File(dir, name));
        } else {
            String dirName = "";
            if (name.contains("/") && !File.separator.equals("/"))
                name = name.replaceAll("/", File.separator + File.separator);
            if (name.contains("\\") && !File.separator.equals("\\"))
                name = name.replaceAll("\\\\", File.separator);

            if (name.lastIndexOf(File.separator) != -1)
                dirName = name.substring(0, name.lastIndexOf(File.separator));
            String fileName = name.substring(name.lastIndexOf(File.separator) + 1, name.length());
            if (unique) {
                fileName = fileName + "." + randomName + "." + createdTime;
            }
            OutputStream out = FileUtils.openOutputStream(FileUtils.create(dir, dirName, fileName));
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(out);
            fileNames.add(fileName);
        }
    }
    IOUtils.closeQuietly(in);
    return fileNames;
}

From source file:utils.APIImporter.java

/**
 * function to unzip the imported folder
 * @param zipFile zip file path/*from w  ww.  j  a  v a2  s.  com*/
 * @param outputFolder folder to copy the zip content
 * @throws APIImportException
 */
private static void unzipFolder(String zipFile, String outputFolder) throws APIImportException {
    byte[] buffer = new byte[1024];

    try {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        FileOutputStream fos = null;
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
            fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(fos);
        //            ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //            //get the zipped file list entry
        //            ZipEntry ze = zis.getNextEntry();
        //            FileOutputStream fos = null;
        //            while(ze!=null){
        //                String fileName = ze.getName();
        //                File newFile = new File(outputFolder + File.separator + fileName);
        //                //create all non exists folders
        //                //else it hit FileNotFoundException for compressed folder
        //                boolean directoryStatus = new File(newFile.getParent()).mkdirs();
        //                while (directoryStatus){
        //                     fos = new FileOutputStream(newFile);
        //                    int len;
        //                    while ((len = zis.read(buffer)) > 0) {
        //                        fos.write(buffer, 0, len);
        //                    }
        //                    ze = zis.getNextEntry();
        //                }
        //            }
        //            zis.closeEntry();
        //            IOUtils.closeQuietly(fos);
        //            IOUtils.closeQuietly(zis);
    } catch (IOException e) {
        String errorMsg = "Cannot extract the zip entries ";
        log.error(errorMsg, e);
        throw new APIImportException(errorMsg, e);
    }
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
**
** Method:   findManifest()//w ww  .  j  av  a  2s .c om
** Input:  String zipFileName  --  The name of the zip file to be used
** Output:   Boolean  --  Signifies whether or not the manifest was found.
**
** Description: This method takes in the name of a zip file and tries to 
**              locate the imsmanifest.xml file
**              
*****************************************************************************/
public static boolean findManifest(String zipFileName) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in findManifest()      ");
        System.out.println("***********************\n");
    }

    boolean rtn = false;

    try {
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));

        ZipEntry entry;
        int flag = 0;

        while ((flag != 1) && (in.available() != 0)) {
            entry = in.getNextEntry();

            if (in.available() != 0) {
                if ((entry.getName()).equalsIgnoreCase("imsmanifest.xml")) {
                    if (_Debug) {
                        System.out.println("Located manifest.... returning true");
                    }
                    flag = 1;
                    rtn = true;
                }
            }
        }

        in.close();
    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
    }
    return rtn;
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
 **/*w  w w .  j  a va2  s .  com*/
 ** Method:   findMetadata()
 ** Input:  String zipFileName  --  The name of the zip file to be used
 ** Output: Boolean  --  Whether or not any xml files were found  
 **
 ** Description: This method takes in the name of a zip file and locates 
 **              all files with an .xml extension 
 **              
 *****************************************************************************/
public static boolean findMetadata(String zipFileName) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in findMetadata()      ");
        System.out.println("***********************\n");
    }

    boolean rtn = false;
    String suffix = ".xml";

    try {
        //  The zip file being searched.
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
        //  An entry in the zip file
        ZipEntry entry;

        while ((in.available() != 0)) {
            entry = in.getNextEntry();

            if (in.available() != 0) {
                if ((entry.getName()).endsWith(suffix)) {
                    rtn = true;
                    if (_Debug) {
                        System.out.println("Other Meta-data located... returning true");
                    }
                }
            }
        }

        in.close();
    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
    }

    return rtn;
}

From source file:com.pari.mw.api.execute.reports.template.ReportTemplateRunner.java

public static File getTopLevelFolder(File zipFile) throws IOException {
    ZipInputStream in = null;
    try {/*from   ww  w  .  j av  a2  s .co m*/
        in = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = null;

        while ((entry = in.getNextEntry()) != null) {
            String outFilename = entry.getName();

            if (entry.isDirectory()) {
                return new File(outFilename);
            }
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return null;
}

From source file:cn.edu.zju.acm.onlinejudge.util.ProblemManager.java

public static ProblemPackage importProblem(InputStream in, ActionMessages messages) {

    Map<String, byte[]> files = new HashMap<String, byte[]>();
    ZipInputStream zis = null;
    try {//from  w ww  . j a v a 2 s.  co  m

        zis = new ZipInputStream(new BufferedInputStream(in));
        // zis = new ZipInputStream(new BufferedInputStream(new FileInputStream("d:/100.zip")));
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {

                // TODO the file may be too big. > 100M
                /*
                 * byte data[] = new byte[(int) entry.getSize()]; int l = 0; while (l < data.length) { int ll =
                 * zis.read(data, l, data.length - l); if (ll < 0) { break; } l += ll; }
                 */
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                CopyUtils.copy(zis, buf);
                files.put(entry.getName(), buf.toByteArray());

            }
            entry = zis.getNextEntry();
        }

    } catch (IOException ioe) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.invalidzip"));
        return null;
    } finally {
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            // ignore
        }
    }
    /*
     * files.clear(); files.put("problems.csv", "3,a\n2,b,true,1,2,3,4,a,b,c\n1,c".getBytes());
     * files.put("1\\checker", "checker".getBytes()); files.put("1\\input", "input".getBytes());
     * files.put("1\\output", "output".getBytes()); files.put("3\\checker", "checker3".getBytes());
     * files.put("3\\input", "input3".getBytes()); files.put("3\\output", "output3".getBytes());
     * files.put("images\\1.jpg", "1".getBytes()); files.put("images\\2\\2.jpg", "2".getBytes());
     */
    if (!files.containsKey(ProblemManager.PROBLEM_CSV_FILE)) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.missingproblemscsv"));
        return null;
    }
    ProblemPackage problemPackage = ProblemManager.parse(files, messages);
    if (messages.size() > 0) {
        return null;
    }
    return problemPackage;
}

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

/**
 * Code to unzip a file. Inspired from// ww w .j av  a2 s  .  co m
 * 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.magnet.tools.tests.MagnetToolStepDefs.java

@Then("^the package \"([^\"]*)\" should contain the following entries:$")
public static void package_should_contain(String packagePath, List<String> entries) throws Throwable {
    File file = new File(expandVariables(packagePath));
    Assert.assertTrue("File " + file + " should exist", file.exists());

    ZipInputStream zip = null;
    Set<String> actualSet;
    try {// ww w  . j av  a  2  s  .c o  m
        FileInputStream fis = new FileInputStream(file);
        zip = new ZipInputStream(fis);
        ZipEntry ze;
        actualSet = new HashSet<String>();
        while ((ze = zip.getNextEntry()) != null) {
            actualSet.add(ze.getName());
        }
    } finally {
        if (null != zip) {
            zip.close();
        }
    }

    for (String e : entries) {
        String expected = expandVariables(e);
        Assert.assertTrue("File " + file + " should contain entry " + expected + ", actual set of entries are "
                + actualSet, actualSet.contains(e));
    }
}