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:herddb.upgrade.ZIPUtils.java

public static List<File> unZip(InputStream fs, File outDir) throws IOException {

    try (ZipInputStream zipStream = new ZipInputStream(fs, StandardCharsets.UTF_8);) {
        ZipEntry entry = zipStream.getNextEntry();
        List<File> listFiles = new ArrayList<>();
        while (entry != null) {
            if (entry.isDirectory()) {
                entry = zipStream.getNextEntry();
                continue;
            }/*w w w  .j  a va  2s.com*/

            String normalized = normalizeFilenameForFileSystem(entry.getName());
            File outFile = new File(outDir, normalized);
            File parentDir = outFile.getParentFile();
            if (parentDir != null && !parentDir.isDirectory()) {
                Files.createDirectories(parentDir.toPath());
            }

            listFiles.add(outFile);
            try (FileOutputStream out = new FileOutputStream(outFile);
                    SimpleBufferedOutputStream oo = new SimpleBufferedOutputStream(out)) {
                IOUtils.copyLarge(zipStream, oo);
            }
            entry = zipStream.getNextEntry();

        }
        return listFiles;
    } catch (IllegalArgumentException ex) {
        throw new IOException(ex);
    }

}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Compress the files in the backup folder for a project.
 * @param projectId The project ID//from ww  w .j  a v a2s. c  o m
 * @throws IOException Any exception when reading/writing data.
 */
public static void compressBackupFolder(final String projectId) throws IOException {
    String backupPath = getBackupPath(projectId);
    if (!Files.isDirectory(Paths.get(backupPath))) {
        // No such directory, so nothing to do.
        return;
    }
    String projectSlug = makeSlug(projectId);
    // The name of the ZIP file that does/will contain all
    // backups for this project.
    Path zipFilePath = Paths.get(backupPath).resolve(projectSlug + ".zip");
    // A temporary ZIP file. Any existing content in the zipFilePath
    // will be copied into this, followed by any other files in
    // the directory that have not yet been added.
    Path tempZipFilePath = Paths.get(backupPath).resolve("temp" + ".zip");

    File tempZipFile = tempZipFilePath.toFile();
    if (!tempZipFile.exists()) {
        tempZipFile.createNewFile();
    }

    ZipOutputStream tempZipOut = new ZipOutputStream(new FileOutputStream(tempZipFile));

    File existingZipFile = zipFilePath.toFile();
    if (existingZipFile.exists()) {
        ZipFile zipIn = new ZipFile(existingZipFile);

        Enumeration<? extends ZipEntry> entries = zipIn.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            logger.debug("compressBackupFolder copying: " + e.getName());
            tempZipOut.putNextEntry(e);
            if (!e.isDirectory()) {
                copy(zipIn.getInputStream(e), tempZipOut);
            }
            tempZipOut.closeEntry();
        }
        zipIn.close();
    }

    File dir = new File(backupPath);
    File[] files = dir.listFiles();

    for (File source : files) {
        if (!source.getName().toLowerCase().endsWith(".zip")) {
            logger.debug("compressBackupFolder compressing and " + "deleting file: " + source.toString());
            if (zipFile(tempZipOut, source)) {
                source.delete();
            }
        }
    }

    tempZipOut.flush();
    tempZipOut.close();
    tempZipFile.renameTo(existingZipFile);
}

From source file:com.aurel.track.admin.customize.category.report.ReportBL.java

/**
 * Save the new template at given location(repository, project)
 * @param repository/*w  w  w .  j  av  a 2s .  c o  m*/
 * @param personID
 * @param project
 * @param templateName
 * @param uploadZip
 * @return an error meassage if exist
 */
public static void saveTemplate(Integer id, ZipInputStream zis) throws IOException {
    // specify buffer size for extraction
    final int BUFFER = 2048;
    // Open Zip file for reading
    File unzipDestinationDirectory = getDirTemplate(id);
    BufferedOutputStream dest = null;
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        File destFile = new File(unzipDestinationDirectory, entry.getName());
        if (destFile.exists()) {
            destFile.delete();
        }
        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();
        // create the parent directory structure if needed
        destinationParent.mkdirs();
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
}

From source file:abfab3d.shapejs.Project.java

private static void extractZip(String zipFile, String outputFolder, Map<String, String> sceneFiles,
        List<String> resources) {
    byte[] buffer = new byte[1024];

    try {//from ww w  .  ja va 2s.com
        //create output directory is not exists
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            // Ignore directories
            if (ze.isDirectory())
                continue;

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            System.out.println("file unzip : " + newFile.getAbsoluteFile());

            FileOutputStream fos = new FileOutputStream(newFile);

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

            // Save path to the script and parameters files
            if (fileName.endsWith(".json")) {
                sceneFiles.put("paramFile", newFile.getAbsolutePath());
            } else if (fileName.endsWith(".js")) {
                sceneFiles.put("scriptFile", newFile.getAbsolutePath());
            } else {
                resources.add(newFile.getAbsolutePath());
            }

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

        zis.closeEntry();
        zis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

/**
 * Uncompresses zipped files//w w w  . j a va 2  s .c  o m
 * @param zippedFile The file to uncompress
 * @param destinationDir Where to put the files
 * @return  list of unzipped files
 * @throws java.io.IOException thrown if there is a problem finding or writing the files
 */
public static List<File> unzip(File zippedFile, File destinationDir) throws IOException {
    int buffer = 2048;

    List<File> unzippedFiles = new ArrayList<File>();

    BufferedOutputStream dest;
    BufferedInputStream is;
    ZipEntry entry;
    ZipFile zipfile = new ZipFile(zippedFile);
    Enumeration e = zipfile.entries();
    while (e.hasMoreElements()) {
        entry = (ZipEntry) e.nextElement();

        is = new BufferedInputStream(zipfile.getInputStream(entry));
        int count;
        byte data[] = new byte[buffer];

        File destFile;

        if (destinationDir != null) {
            destFile = new File(destinationDir, entry.getName());
        } else {
            destFile = new File(entry.getName());
        }

        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, buffer);
        try {
            while ((count = is.read(data, 0, buffer)) != -1) {
                dest.write(data, 0, count);
            }

            unzippedFiles.add(destFile);
        } finally {
            dest.flush();
            dest.close();
            is.close();
        }
    }

    return unzippedFiles;
}

From source file:it.geosolutions.tools.compress.file.Extractor.java

/**
 * Inflate the provided {@link ZipFile} in the provided output directory.
 * /* w  w  w .  j  av a  2  s.c  om*/
 * @param archive
 *            the {@link ZipFile} to inflate.
 * @param outputDirectory
 *            the directory where to inflate the archive.
 * @throws IOException
 *             in case something bad happens.
 * @throws FileNotFoundException
 *             in case something bad happens.
 */
public static void inflate(ZipFile archive, File outputDirectory, String fileName)
        throws IOException, FileNotFoundException {

    final Enumeration<? extends ZipEntry> entries = archive.entries();
    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (!entry.isDirectory()) {
                final String name = entry.getName();
                final String ext = FilenameUtils.getExtension(name);
                final InputStream in = new BufferedInputStream(archive.getInputStream(entry));
                final File outFile = new File(outputDirectory,
                        fileName != null ? new StringBuilder(fileName).append(".").append(ext).toString()
                                : name);
                final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));

                IOUtils.copyStream(in, out, true, true);
            }
        }
    } finally {
        try {
            archive.close();
        } catch (Throwable e) {
            if (LOGGER.isTraceEnabled())
                LOGGER.error("unable to close archive.\nMessage is: " + e.getMessage(), e);
        }
    }

}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * Extracts the packageFile and writes its content in temporary directory
 *
 * @param packageFile the packageFile (zip format)
 * @param tempDir the tempDir directory/*from w w  w .ja  va 2  s  . c o m*/
 */
public static void extractPackage(File packageFile, File tempDir) throws SoundPackageException {

    if (packageFile == null) {
        throw new SoundPackageException(new IllegalArgumentException("missing package file"));
    }

    ZipFile packageZip = null;
    try {
        packageZip = new ZipFile(packageFile);
        Enumeration<?> entries = packageZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String entryName = entry.getName();
            if (log.isDebugEnabled()) {
                log.debug("ZipEntry name: " + entryName);
            }
            if (entry.isDirectory()) {
                File dir = new File(tempDir, entryName);
                if (dir.mkdirs())
                    log.info("successfully created dir: " + dir.getAbsolutePath());
            } else {
                FileUtil.createFileFromInputStream(getPackageEntryStream(packageFile, entryName),
                        tempDir + File.separator + entryName);
            }
        }
    } catch (FileNotFoundException ex) {
        throw new SoundPackageException(ex);
    } catch (IOException ex) {
        throw new SoundPackageException(ex);
    } finally {
        try {
            if (packageZip != null)
                packageZip.close();
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}

From source file:com.microsoft.intellij.AzurePlugin.java

private static void unzip(String zipFilePath, String destDirectory) throws IOException {
    File destDir = new File(destDirectory);
    if (!destDir.exists()) {
        destDir.mkdir();//from w  w w. j  a v  a  2 s . c o  m
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = destDirectory + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:it.geosolutions.geofence.gui.server.utility.IoUtility.java

/**
 * Decompress.// w ww.  ja  v  a 2s  .  c  om
 *
 * @param prefix
 *            the prefix
 * @param inputFile
 *            the input file
 * @param tempFile
 *            the temp file
 * @return the file
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static File decompress(final String prefix, final File inputFile, final File tempFile)
        throws IOException {
    final File tmpDestDir = createTodayPrefixedDirectory(prefix, new File(tempFile.getParent()));

    ZipFile zipFile = new ZipFile(inputFile);

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {

        ZipEntry entry = (ZipEntry) entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);

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

            continue;
        }

        File newFile = new File(tmpDestDir, entry.getName());

        FileOutputStream fos = new FileOutputStream(newFile);
        try {
            byte[] buf = new byte[1024];
            int len;

            while ((len = stream.read(buf)) >= 0) {
                saveCompressedStream(buf, fos, len);
            }

        } catch (IOException e) {
            zipFile.close();

            IOException ioe = new IOException("Not valid ZIP archive file type.");
            ioe.initCause(e);
            throw ioe;
        } finally {
            fos.flush();
            fos.close();

            stream.close();
        }
    }
    zipFile.close();

    if ((tmpDestDir.listFiles().length == 1) && (tmpDestDir.listFiles()[0].isDirectory())) {
        return getShpFile(tmpDestDir.listFiles()[0]);
    }

    // File[] files = tmpDestDir.listFiles(new FilenameFilter() {
    //
    // public boolean accept(File dir, String name) {
    // return FilenameUtils.getExtension(name).equalsIgnoreCase("shp");
    // }
    // });
    //
    // return files.length > 0 ? files[0] : null;

    return getShpFile(tmpDestDir);
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * Extracts only the local dependencies used from a map from a DXP package.
 * @param zipFile/*w  w  w  . j a v a2 s. co  m*/
 * @param mapEntry
 * @param outputDir
 * @param dxpOptions
 * @throws Exception 
 */
private static void extractMap(ZipFile zipFile, ZipEntry mapEntry, File outputDir,
        MapBosProcessorOptions dxpOptions) throws Exception {
    Map<URI, Document> domCache = new HashMap<URI, Document>();

    if (!dxpOptions.isQuiet())
        log.info("Extracting map " + mapEntry.getName() + "...");

    BosConstructionOptions bosOptions = new BosConstructionOptions(log, domCache);

    InputSource source = new InputSource(zipFile.getInputStream(mapEntry));

    File dxpFile = new File(zipFile.getName());

    URL baseUri = new URL("jar:" + dxpFile.toURI().toURL().toExternalForm() + "!/");
    URL mapUrl = new URL(baseUri, mapEntry.getName());

    source.setSystemId(mapUrl.toExternalForm());

    Document rootMap = DomUtil.getDomForSource(source, bosOptions, false);
    DitaBoundedObjectSet mapBos = DitaBosHelper.calculateMapBos(bosOptions, log, rootMap);

    MapCopyingBosVisitor visitor = new MapCopyingBosVisitor(outputDir);
    visitor.visit(mapBos);
    if (!dxpOptions.isQuiet())
        log.info("Map extracted.");
}