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.asakusafw.testdriver.compiler.util.DeploymentUtil.java

private static void mergeEntries(ZipOutputStream zip, File file, Set<String> saw) throws IOException {
    try (ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {
        while (true) {
            ZipEntry entry = in.getNextEntry();
            if (entry == null) {
                break;
            }//from w w  w  . j a  v  a  2 s  .com
            if (saw.contains(entry.getName())) {
                continue;
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Copy into archive: {} -> {}", entry.getName(), file);
            }
            saw.add(entry.getName());
            zip.putNextEntry(new ZipEntry(entry.getName()));
            copyStream(in, zip);
        }
    }
}

From source file:fr.inria.atlanmod.neoemf.benchmarks.datastore.helper.BackendHelper.java

private static List<String> getZipResources() throws IOException {
    if (isNull(AVAILABLE_RESOURCES)) {
        AVAILABLE_RESOURCES = new ArrayList<>();

        try (ZipInputStream inputStream = new ZipInputStream(
                BackendHelper.class.getResourceAsStream("/" + ZIP_FILENAME))) {
            ZipEntry entry = inputStream.getNextEntry();
            while (nonNull(entry)) {
                if (!entry.isDirectory() && checkValidResource(entry.getName())) {
                    AVAILABLE_RESOURCES.add(new File(entry.getName()).getName());
                }/*  ww  w  . jav a 2  s. c om*/
                inputStream.closeEntry();
                entry = inputStream.getNextEntry();
            }
        }
    }
    return AVAILABLE_RESOURCES;
}

From source file:de.pksoftware.springstrap.sapi.util.WebappZipper.java

/**
 * Unzip it/*from  w  w  w.  jav  a2  s .  c  om*/
 * @param zipFile input zip file
 * @param output zip file output folder
 */
public static void unzip(String zipFile, String outputFolder) {
    logger.info("Unzipping {} into {}.", zipFile, outputFolder);

    byte[] buffer = new byte[1024];

    try {

        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //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(outputFolder + File.separator + fileName);

            logger.debug("Unzipping: {}", newFile.getAbsoluteFile());

            //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();

        logger.debug("Unzipping {} completed.", zipFile);

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

public static boolean unzip(ZipFile zip, File dest, List<String> files) throws MPTException {
    boolean returnValue = true;
    try {// w w  w.  jav  a  2  s.c  om
        List<String> existingDirs = new ArrayList<>();
        Enumeration<? extends ZipEntry> en = zip.entries();
        entryLoop: while (en.hasMoreElements()) {
            ZipEntry entry = en.nextElement();
            String name = entry.getName().startsWith("./")
                    ? entry.getName().substring(2, entry.getName().length())
                    : entry.getName();
            File file = new File(dest, name);
            if (entry.isDirectory()) {
                if (file.exists()) {
                    if (DISALLOW_MERGE) {
                        existingDirs.add(name);
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract directory " + name + ": already exists");
                    }
                }
            } else {
                files.add(name);
                for (String dir : DISALLOWED_DIRECTORIES) {
                    if (file.getPath().startsWith(dir)) {
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                    + ": parent directory \"" + dir + "\" is not allowed");
                        continue entryLoop;
                    }
                }
                if (DISALLOW_MERGE) {
                    for (String dir : existingDirs) {
                        if (file.getPath().substring(2, file.getPath().length()).replace(File.separator, "/")
                                .startsWith(dir)) {
                            continue entryLoop;
                        }
                    }
                }
                if (!DISALLOW_OVERWRITE || !file.exists()) {
                    file.getParentFile().mkdirs();
                    for (String ext : DISALLOWED_EXTENSIONS) {
                        if (file.getName().endsWith(ext)) {
                            if (VERBOSE)
                                Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                        + ": extension \"" + ext + "\" is not allowed");
                            returnValue = false;
                            continue entryLoop;
                        }
                    }
                    BufferedInputStream bIs = new BufferedInputStream(zip.getInputStream(entry));
                    int b;
                    byte[] buffer = new byte[1024];
                    FileOutputStream fOs = new FileOutputStream(file);
                    BufferedOutputStream bOs = new BufferedOutputStream(fOs, 1024);
                    while ((b = bIs.read(buffer, 0, 1024)) != -1)
                        bOs.write(buffer, 0, b);
                    bOs.flush();
                    bOs.close();
                    bIs.close();
                } else {
                    if (VERBOSE)
                        Main.log.warning(
                                "Refusing to extract " + name + " from " + zip.getName() + ": already exists");
                    returnValue = false;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace(); //TODO
        throw new MPTException(ERROR_COLOR + "Failed to extract archive!");
    }
    return returnValue;
}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();//www .  ja  v a2 s .  c  o m

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

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

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final File extract(File compressedFile, String export) throws IOException {
    log.trace("Compressed file {}", compressedFile);

    File file = null;/*w  w w  .  ja v a  2 s.c o  m*/
    if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) {
        file = unBZip2(compressedFile);
    } else if (compressedFile.getName().toLowerCase().endsWith("tar.gz")) {
        file = unTarGz(compressedFile);
    } else if (compressedFile.getName().toLowerCase().endsWith("gz")) {
        file = unGzip(compressedFile);
    } else {
        ZipFile zipFolder = new ZipFile(compressedFile);
        Enumeration<?> enu = zipFolder.entries();

        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();

            String name = zipEntry.getName();
            long size = zipEntry.getSize();
            long compressedSize = zipEntry.getCompressedSize();
            log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", name, size, compressedSize);

            file = new File(compressedFile.getParentFile() + File.separator + name);
            if (!file.exists() || WdmConfig.getBoolean("wdm.override")) {
                if (name.endsWith("/")) {
                    file.mkdirs();
                    continue;
                }

                File parent = file.getParentFile();
                if (parent != null) {
                    parent.mkdirs();
                }

                InputStream is = zipFolder.getInputStream(zipEntry);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int length;
                while ((length = is.read(bytes)) >= 0) {
                    fos.write(bytes, 0, length);
                }
                is.close();
                fos.close();
                file.setExecutable(true);
            } else {
                log.debug(file + " already exists");
            }

        }
        zipFolder.close();
    }

    file = checkPhantom(compressedFile, export);

    log.trace("Resulting binary file {}", file.getAbsoluteFile());
    return file.getAbsoluteFile();
}

From source file:fr.inria.atlanmod.neoemf.benchmarks.datastore.helper.BackendHelper.java

private static File extractFromZip(String filename, Path outputDir) throws IOException {
    File outputFile = null;/*from w  w  w  .  j a v a 2s. c  o  m*/
    boolean fileFound = false;
    try (ZipInputStream inputStream = new ZipInputStream(
            BackendHelper.class.getResourceAsStream("/" + ZIP_FILENAME))) {
        ZipEntry entry = inputStream.getNextEntry();
        while (nonNull(entry) || !fileFound) {
            if (!entry.isDirectory() && Objects.equals(new File(entry.getName()).getName(), filename)) {
                outputFile = extractEntryFromZip(inputStream, entry, outputDir);
                fileFound = true;
            }
            inputStream.closeEntry();
            entry = inputStream.getNextEntry();
        }
    }
    return outputFile;
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSUtil.java

public static void copyDynamicResource(Consumer<FileTypeStream> parserManager, String inputResource,
        FileObject webRoot, Function<String, String> pathResolver, ProgressHandler handler) throws IOException {
    InputStream inputStream = loadResource(inputResource);
    try (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }//from ww  w.  j  a v  a2s . c  o m
            boolean skipParsing = true;
            String entryName = entry.getName();
            if (entryName.endsWith(".ejs")) {
                skipParsing = false;
                entryName = entryName.substring(0, entryName.lastIndexOf("."));
            }
            String targetPath = pathResolver.apply(entryName);
            if (targetPath == null) {
                continue;
            }
            handler.progress(targetPath);
            FileObject target = org.openide.filesystems.FileUtil.createData(webRoot, targetPath);
            FileLock lock = target.lock();
            try (OutputStream outputStream = target.getOutputStream(lock);) {
                parserManager.accept(new FileTypeStream(entryName, zipInputStream, outputStream, skipParsing));
                zipInputStream.closeEntry();
            } finally {
                lock.releaseLock();
            }
        }
    } catch (Throwable ex) {
        Exceptions.printStackTrace(ex);
        System.out.println("InputResource : " + inputResource);
    }
}

From source file:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java

public static File unzipFile(File zipFile, File file) {
    System.out.println("path to zipFile: " + zipFile.getPath());
    System.out.println("file to extract: " + file.getPath());
    String fileName = null;/*  ww  w . j a  v a 2 s  .  c o  m*/

    try {
        zipFile.mkdir();
        BufferedOutputStream dest = null;
        BufferedInputStream is = null;
        ZipEntry entry;
        ZipFile zipfile = new ZipFile(zipFile);
        Enumeration e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = (ZipEntry) e.nextElement();
            // System.out.println(entry.getName());
            if (entry.getName().substring(entry.getName().indexOf("/") + 1).equals(file.getName())) {
                //   if (entry.getName().contains(file.getName())){
                System.out.println("firmware to extract found.");

                String tempFolder = System.getProperty("user.dir") + File.separatorChar + "tmp"
                        + File.separatorChar;
                if (System.getProperty("os.name").toLowerCase().contains("mac")) {
                    tempFolder = System.getProperty("user.home")
                            + "/Library/Preferences/kkMulticopterFlashTool/";
                }

                String newDir;
                if (entry.getName().indexOf("/") == -1) {
                    newDir = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
                } else {
                    newDir = entry.getName().substring(0, entry.getName().indexOf("/"));
                }
                String folder = tempFolder + newDir;
                System.out.println("Create folder: " + folder);
                if ((new File(folder).mkdir())) {
                    System.out.println("Done.");
                    ;
                }

                System.out.println("Extracting: " + entry);
                is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[2048];
                fileName = tempFolder + entry.getName();
                FileOutputStream fos = new FileOutputStream(tempFolder + entry.getName());
                dest = new BufferedOutputStream(fos, 2048);
                while ((count = is.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
                break;
            }
        }
    } catch (ZipException e) {
        zipFile.delete();
        kk.err(Translatrix._("error.zipfileDamaged"));
        kk.err(Translatrix._("reportProblem"));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new File(fileName);
}

From source file:io.github.jeddict.jcode.util.FileUtil.java

public static void copyStaticResource(String inputTemplatePath, FileObject toDir, String targetFolder,
        ProgressHandler handler) throws IOException {
    InputStream stream = loadResource(inputTemplatePath);
    try (ZipInputStream inputStream = new ZipInputStream(stream)) {
        ZipEntry entry;
        while ((entry = inputStream.getNextEntry()) != null) {
            if (entry.getName().lastIndexOf('.') == -1) { //skip if not file
                continue;
            }// w w  w  .jav  a 2 s. c  o m
            String targetPath = StringUtils.isBlank(targetFolder) ? entry.getName()
                    : targetFolder + '/' + entry.getName();
            if (handler != null) {
                handler.progress(targetPath);
            }
            FileObject target = org.openide.filesystems.FileUtil.createData(toDir, targetPath);
            FileLock lock = target.lock();
            try (OutputStream outputStream = target.getOutputStream(lock)) {
                for (int c = inputStream.read(); c != -1; c = inputStream.read()) {
                    outputStream.write(c);
                }
                inputStream.closeEntry();
            } finally {
                lock.releaseLock();
            }
        }
    }
}