Example usage for java.util.zip ZipEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

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

/**
 * Code to unzip a file. Inspired from//from  w w w .j  a v  a2  s  .  com
 * 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:it.geosolutions.tools.compress.file.Extractor.java

public static void unZip(File inputZipFile, File outputDir) throws IOException, CompressorException {
    if (inputZipFile == null || outputDir == null) {
        throw new CompressorException("Unzip: with null parameters");
    }/*from  w  ww .  j a  va  2 s.c  om*/

    if (!outputDir.exists()) {
        if (!outputDir.mkdirs()) {
            throw new CompressorException("Unzip: Unable to create directory structure: " + outputDir);
        }
    }

    final int BUFFER = Conf.getBufferSize();

    ZipInputStream zipInputStream = null;
    try {
        // Open Zip file for reading
        zipInputStream = new ZipInputStream(new FileInputStream(inputZipFile));
    } catch (FileNotFoundException fnf) {
        throw new CompressorException("Unzip: Unable to find the input zip file named: " + inputZipFile);
    }

    // extract file if not a directory
    BufferedInputStream bis = new BufferedInputStream(zipInputStream);
    // grab a zip file entry
    ZipEntry entry = null;
    while ((entry = zipInputStream.getNextEntry()) != null) {
        // Process each entry

        File currentFile = new File(outputDir, entry.getName());

        FileOutputStream fos = null;
        BufferedOutputStream dest = null;
        try {
            int currentByte;
            // establish buffer for writing file
            byte data[] = new byte[BUFFER];

            // write the current file to disk
            fos = new FileOutputStream(currentFile);
            dest = new BufferedOutputStream(fos, BUFFER);

            // read and write until last byte is encountered
            while ((currentByte = bis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, currentByte);
            }
        } catch (IOException ioe) {

        } finally {
            try {
                if (dest != null) {
                    dest.flush();
                    dest.close();
                }
                if (fos != null)
                    fos.close();
            } catch (IOException ioe) {
                throw new CompressorException(
                        "Unzip: unable to close the zipInputStream: " + ioe.getLocalizedMessage());
            }
        }
    }
    try {
        if (zipInputStream != null)
            zipInputStream.close();
    } catch (IOException ioe) {
        throw new CompressorException(
                "Unzip: unable to close the zipInputStream: " + ioe.getLocalizedMessage());
    }
    try {
        if (bis != null)
            bis.close();
    } catch (IOException ioe) {
        throw new CompressorException(
                "Unzip: unable to close the Buffered zipInputStream: " + ioe.getLocalizedMessage());
    }
}

From source file:com.ikon.util.ReportUtils.java

/**
 * Execute report/*from   ww w.  j  a  v  a 2s.  com*/
 */
public static ByteArrayOutputStream execute(Report rp, final Map<String, Object> params, final int format)
        throws JRException, IOException, EvalError {
    ByteArrayOutputStream baos = null;
    ByteArrayInputStream bais = null;
    ZipInputStream zis = null;
    Session dbSession = null;

    try {
        baos = new ByteArrayOutputStream();
        bais = new ByteArrayInputStream(SecureStore.b64Decode(rp.getFileContent()));
        JasperReport jr = null;

        // Obtain or compile report
        if (ReportUtils.MIME_JRXML.equals(rp.getFileMime())) {
            log.debug("Report type: JRXML");
            jr = JasperCompileManager.compileReport(bais);
        } else if (ReportUtils.MIME_JASPER.equals(rp.getFileMime())) {
            log.debug("Report type: JASPER");
            jr = (JasperReport) JRLoader.loadObject(bais);
        } else if (ReportUtils.MIME_REPORT.equals(rp.getFileMime())) {
            zis = new ZipInputStream(bais);
            ZipEntry zi = null;

            while ((zi = zis.getNextEntry()) != null) {
                if (!zi.isDirectory()) {
                    String mimeType = MimeTypeConfig.mimeTypes.getContentType(zi.getName());

                    if (ReportUtils.MIME_JRXML.equals(mimeType)) {
                        log.debug("Report type: JRXML inside ARCHIVE");
                        jr = JasperCompileManager.compileReport(zis);
                        break;
                    } else if (ReportUtils.MIME_JASPER.equals(mimeType)) {
                        log.debug("Report type: JASPER inside ARCHIVE");
                        jr = (JasperReport) JRLoader.loadObject(zis);
                        break;
                    }
                }
            }
        }

        // Guess if SQL or BSH
        if (jr != null) {
            JRQuery query = jr.getQuery();
            String tq = query.getText().trim();

            if (tq.toUpperCase().startsWith("SELECT")) {
                log.debug("Report type: DATABASE");
                dbSession = HibernateUtil.getSessionFactory().openSession();
                executeDatabase(dbSession, baos, jr, params, format);
            } else {
                log.debug("Report type: SCRIPTING");
                ReportUtils.generateReport(baos, jr, params, format);
            }
        }

        return baos;
    } finally {
        HibernateUtil.close(dbSession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
        IOUtils.closeQuietly(zis);
    }
}

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

/****************************************************************************
**
** Method:   extract()/*  ww  w.j a v a2  s  .  c  om*/
** Input:  String zipFileName  --  The name of the zip file to be used
**         Sting  extractedFile  --  The name of the file to be extracted 
**                                   from the zip    
** Output:   none
**
** Description: This method takes in the name of a zip file and a file to
**              be extracted from the zip format.  The method locates the
**              file and extracts into the '.' directory.
**              
*****************************************************************************/
public static String extract(String zipFileName, String extractedFile, String pathOfExtract) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in extract()           ");
        System.out.println("***********************");
        System.out.println("zip file: " + zipFileName);
        System.out.println("file to extract: " + extractedFile);
    }

    String nameOfExtractedFile = new String("");
    System.out.println("-----LMSPackageHandler-extract()----");
    System.out.println("zipFileName=" + zipFileName);
    System.out.println("extractedFile=" + extractedFile);
    System.out.println("pathOfExtract=" + pathOfExtract);
    try {
        String pathAndName = new String("");
        int index = zipFileName.lastIndexOf("\\") + 1;
        zipFileName = zipFileName.substring(index);
        System.out.println("---zipFileName=" + zipFileName);
        //  Input stream for the zip file (package)
        ZipInputStream in = new ZipInputStream(new FileInputStream(pathOfExtract + "\\" + zipFileName));

        //  Cut the path off of the name of the file. (for writing the file)
        int indexOfFileBeginning = extractedFile.lastIndexOf("/") + 1;
        System.out.println("---indexOfFileBeginning=" + indexOfFileBeginning);
        nameOfExtractedFile = extractedFile.substring(indexOfFileBeginning);
        System.out.println("---nameOfExtractedFile=" + nameOfExtractedFile);
        pathAndName = pathOfExtract + "\\" + nameOfExtractedFile;
        System.out.println("pathAndName=" + pathAndName);
        //  Ouput stream for the extracted file
        //*************************************
        //*************************************
        OutputStream out = new FileOutputStream(pathAndName);
        //OutputStream out = new FileOutputStream(nameOfExtractedFile);

        ZipEntry entry;
        byte[] buf = new byte[1024];
        int len;
        int flag = 0;

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

            if ((entry.getName()).equalsIgnoreCase(extractedFile)) {
                if (_Debug) {
                    System.out.println("Found file to extract...  extracting to " + pathOfExtract);
                }
                flag = 1;
            }
        }

        while ((len = in.read(buf)) > 0) {

            out.write(buf, 0, len);
        }

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

From source file:net.ftb.util.FileUtils.java

public static void backupExtract(String zipLocation, String outputLocation) {
    Logger.logInfo("Extracting (Backup way)");
    byte[] buffer = new byte[1024];
    ZipInputStream zis = null;// w  ww. j av  a 2 s . c  om
    ZipEntry ze;
    try {
        File folder = new File(outputLocation);
        if (!folder.exists()) {
            folder.mkdir();
        }
        zis = new ZipInputStream(new FileInputStream(zipLocation));
        ze = zis.getNextEntry();
        while (ze != null) {
            File newFile = new File(outputLocation, ze.getName());
            newFile.getParentFile().mkdirs();
            if (!ze.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.flush();
                fos.close();
            }
            ze = zis.getNextEntry();
        }
    } catch (IOException ex) {
        Logger.logError("Error while extracting zip", ex);
    } finally {
        try {
            zis.closeEntry();
            zis.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.vvote.verifierlibrary.utils.io.IOUtils.java

/**
 * Utility class to extract a zip file//  www .  j av a2s .  c o  m
 * 
 * @param filepath
 * @return the location of the extract zip file
 * @throws IOException
 */
public static String extractZipFile(String filepath) throws IOException {

    if (IOUtils.checkExtension(FileType.ZIP, filepath)) {
        try (ZipFile zipFile = new ZipFile(filepath)) {

            // files in zip file
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            // current zip directory
            File zipDirectory = new File(filepath);

            // output directory - doesn't include the .zip extension
            File outputDirectory = new File(
                    IOUtils.join(zipDirectory.getParent(), IOUtils.getFileNameWithoutExtension(filepath)));

            // make directory if not exists
            if (!outputDirectory.exists()) {
                outputDirectory.mkdir();
            }

            InputStream is = null;
            FileOutputStream fos = null;
            byte[] bytes = null;

            int length = 0;

            // loop over each file in zip file
            while (entries.hasMoreElements()) {
                ZipEntry zipEntry = entries.nextElement();

                String entryName = zipEntry.getName();

                // current output file
                File file = new File(IOUtils.join(outputDirectory.getPath(), entryName));

                File currentOutputFile = new File(getFilePathWithoutExtension(file.getPath()));

                if (currentOutputFile.exists()) {
                    if (getFileNameWithoutExtension(entryName)
                            .contains(CommitFileNames.WBB_UPLOAD.getFileName())) {

                        try (ZipFile currentZipFile = new ZipFile(file)) {
                            Enumeration<? extends ZipEntry> currentZipEntries = currentZipFile.entries();

                            long currentUncompressedZipSize = currentZipEntries.nextElement().getSize();
                            long currentDirectorySize = FileUtils.sizeOfDirectory(currentOutputFile);

                            if (currentUncompressedZipSize == currentDirectorySize) {
                                continue;
                            }
                        }
                    }
                }

                // if directory make it
                if (entryName.endsWith("/")) {
                    file.mkdirs();
                } else {

                    // write current input zip file to output location
                    is = zipFile.getInputStream(zipEntry);
                    fos = new FileOutputStream(file);
                    bytes = new byte[1024];

                    while ((length = is.read(bytes)) >= 0) {
                        fos.write(bytes, 0, length);
                    }
                    is.close();
                    fos.close();
                }
            }

            return outputDirectory.getPath();
        }
    }
    logger.error("Provided filepath: {} does not point to a valid zip file", filepath);
    throw new IOException("Provided filepath: " + filepath + " does not point to a valid zip file");
}

From source file:org.opendatakit.api.forms.FormService.java

static Map<String, byte[]> processZipInputStream(ZipInputStream zipInputStream) throws IOException {
    int c;/*from  w w  w .jav  a2 s . com*/
    Map<String, byte[]> files = new HashMap<>();
    byte buffer[] = new byte[2084];
    ByteArrayOutputStream tempBAOS;
    ZipEntry zipEntry;
    while ((zipEntry = zipInputStream.getNextEntry()) != null) {
        if (!(zipEntry.isDirectory())) {
            tempBAOS = new ByteArrayOutputStream();
            while ((c = zipInputStream.read(buffer, 0, 2048)) > -1) {
                tempBAOS.write(buffer, 0, c);
            }
            files.put("tables" + BasicConsts.FORWARDSLASH + zipEntry.getName(), tempBAOS.toByteArray());
        }
    }
    return files;
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

/**
 * extracts a zip-file and returns references to the unziped files. If the file passed to this method
 * is not a zip-file, a reference to the file is returned.
 * /*from   w  ww .  j av  a  2  s .  c om*/
 * @param fileName
 * @return
 * @throws Exception
 */
public static Set<File> extractZip(String fileName) throws Exception {
    File zipf = new File((new StringBuilder("luxid/")).append(fileName).toString());

    Set<File> toBeUploaded = new HashSet<File>();
    if (zipf.getName().endsWith(".zip")) {
        ZipFile zip = new ZipFile(zipf);
        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                logger.info((new StringBuilder("Extracting directory: ")).append(entry.getName()).toString());
                GenUtil.mkdir(new File(entry.getName()));
            } else {
                logger.info((new StringBuilder("Extracting file: ")).append(entry.getName()).toString());
                String entryPath = "luxid/" + entry.getName();
                FileOutputStream fileOutputStream = null;
                InputStream zipEntryStream = zip.getInputStream(entry);
                try {
                    fileOutputStream = new FileOutputStream(entryPath);
                    IOUtils.copy(zipEntryStream, fileOutputStream);
                } finally {
                    closeQuietly(zipEntryStream);
                    closeQuietly(fileOutputStream);
                }
                toBeUploaded.add(new File(entryPath));
            }
        }

        zip.close();
    } else {
        toBeUploaded.add(zipf);
    }

    return toBeUploaded;
}

From source file:com.gisgraphy.domain.geoloc.importer.ImporterHelper.java

/**
 * unzip a file in the same directory as the zipped file
 * //from   w  ww . ja v  a  2 s  .  co m
 * @param file
 *            The file to unzip
 */
public static void unzipFile(File file) {
    logger.info("will Extracting file: " + file.getName());
    Enumeration<? extends ZipEntry> entries;
    ZipFile zipFile;

    try {
        zipFile = new ZipFile(file);

        entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (entry.isDirectory()) {
                // Assume directories are stored parents first then
                // children.
                (new File(entry.getName())).mkdir();
                continue;
            }

            logger.info("Extracting file: " + entry.getName() + " to " + file.getParent() + File.separator
                    + entry.getName());
            copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                    new FileOutputStream(file.getParent() + File.separator + entry.getName())));
        }

        zipFile.close();
    } catch (IOException e) {
        logger.error("can not unzip " + file.getName() + " : " + e.getMessage());
        throw new ImporterException(e);
    }
}

From source file:gov.nasa.ensemble.resources.ResourceUtil.java

public static IProject unzipProject(String projectName, ZipInputStream zis, IProgressMonitor monitor)
        throws CoreException, IOException {
    final String dirPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath();
    if (monitor == null)
        monitor = new NullProgressMonitor();
    try {//  w w  w .  j  ava 2  s. c o  m
        monitor.beginTask("Loading " + projectName, 300);
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            File to = (!new File(dirPath, entry.getName()).getAbsolutePath().contains(projectName))
                    ? new File(dirPath + File.separator + projectName, entry.getName())
                    : new File(dirPath, entry.getName());
            if (entry.isDirectory()) {
                if (!to.exists() && !to.mkdirs()) {
                    throw new IOException("Error creating directory: " + to);
                }
            } else {
                File parent = to.getParentFile();
                if (parent != null && !parent.exists() && !parent.mkdirs()) {
                    throw new IOException("Error creating directory: " + parent);
                }
                FileOutputStream fos = new FileOutputStream(to);
                try {
                    monitor.subTask("Expanding: " + to.getName());
                    IOUtils.copy(zis, fos);
                } finally {
                    IOUtils.closeQuietly(fos);
                }
            }
            monitor.worked(10);
        }
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
        project.create(null);
        project.open(null);
        return project;
    } catch (IOException e) {
        throw new CoreException(
                new ExceptionStatus(EnsembleResourcesPlugin.PLUGIN_ID, "adding project to workspace", e));
    } finally {
        zis.close();
        monitor.done();
    }
}