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:be.fedict.eid.applet.service.signer.odf.ODFUtil.java

/**
 * Get a list of all the files / zip entries in an ODF package
 * //from  w  w  w . j  a v a 2 s. c om
 * @param odfInputStream
 * @return
 * @throws IOException
 */
public static List getZipEntriesAsList(InputStream odfInputStream) throws IOException {
    ArrayList list = new ArrayList();

    ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
    ZipEntry zipEntry;

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        list.add(zipEntry.getName());
    }
    return list;
}

From source file:com.plotsquared.iserver.util.FileUtils.java

/**
 * Add files to a zip file/*ww  w .j  a  v  a  2s.c  o m*/
 *
 * @param zipFile Zip File
 * @param files   Files to add to the zip
 * @param delete  If the original files should be deleted
 * @throws Exception If anything goes wrong
 */
public static void addToZip(final File zipFile, final File[] files, final boolean delete) throws Exception {
    Assert.notNull(zipFile, files);

    if (!zipFile.exists()) {
        if (!zipFile.createNewFile()) {
            throw new RuntimeException("Couldn't create " + zipFile);
        }
    }

    final File temporary = File.createTempFile(zipFile.getName(), "");
    //noinspection ResultOfMethodCallIgnored
    temporary.delete();

    if (!zipFile.renameTo(temporary)) {
        throw new RuntimeException("Couldn't rename " + zipFile + " to " + temporary);
    }

    final byte[] buffer = new byte[1024 * 16]; // 16mb

    ZipInputStream zis = new ZipInputStream(new FileInputStream(temporary));
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry e = zis.getNextEntry();
    while (e != null) {
        String n = e.getName();

        boolean no = true;
        for (File f : files) {
            if (f.getName().equals(n)) {
                no = false;
                break;
            }
        }

        if (no) {
            zos.putNextEntry(new ZipEntry(n));
            int len;
            while ((len = zis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
        e = zis.getNextEntry();
    }
    zis.close();
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        zos.putNextEntry(new ZipEntry(file.getName()));

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

        zos.closeEntry();
        in.close();
    }
    zos.close();
    temporary.delete();

    if (delete) {
        for (File f : files) {
            f.delete();
        }
    }
}

From source file:Main.java

/**
 * /*from  w w  w. j av a  2 s .  com*/
 * @param zipFile
 *            zip file
 * @param folderName
 *            folder to load
 * @return list of entry in the folder
 * @throws ZipException
 * @throws IOException
 */
public static List<ZipEntry> loadFiles(File zipFile, String folderName) throws ZipException, IOException {
    Log.d("loadFiles", folderName);
    long start = System.currentTimeMillis();
    FileInputStream fis = new FileInputStream(zipFile);
    BufferedInputStream bis = new BufferedInputStream(fis);
    ZipInputStream zis = new ZipInputStream(bis);

    ZipEntry zipEntry = null;
    List<ZipEntry> list = new LinkedList<ZipEntry>();
    String folderLowerCase = folderName.toLowerCase();
    int counter = 0;
    while ((zipEntry = zis.getNextEntry()) != null) {
        counter++;
        String zipEntryName = zipEntry.getName();
        Log.d("loadFiles.zipEntry.getName()", zipEntryName);
        if (zipEntryName.toLowerCase().startsWith(folderLowerCase) && !zipEntry.isDirectory()) {
            list.add(zipEntry);
        }
    }
    Log.d("Loaded 1", counter + " files, took: " + (System.currentTimeMillis() - start) + " milliseconds.");
    zis.close();
    bis.close();
    fis.close();
    return list;
}

From source file:com.nuvolect.deepdive.probe.ApkZipUtil.java

/**
 * Unzip while excluding XML files into the target directory.
 * The added structure is updated to reflect any new files and directories created.
 * Overwrite files when requested./*from   ww  w  . j  a  v  a  2 s. c  o m*/
 * @param zipOmni
 * @param targetDir
 * @param progressStream
 * @return
 */
public static boolean unzipAllExceptXML(OmniFile zipOmni, OmniFile targetDir, ProgressStream progressStream) {

    String volumeId = zipOmni.getVolumeId();
    String rootFolderPath = targetDir.getPath();
    boolean DEBUG = true;

    ZipInputStream zis = new ZipInputStream(zipOmni.getFileInputStream());
    ZipEntry entry = null;
    try {
        while ((entry = zis.getNextEntry()) != null) {

            if (entry.isDirectory()) {

                OmniFile dir = new OmniFile(volumeId, entry.getName());
                if (dir.mkdir()) {

                    if (DEBUG)
                        LogUtil.log(LogUtil.LogType.OMNI_ZIP, "dir created: " + dir.getPath());
                }
            } else {

                String path = rootFolderPath + "/" + entry.getName();
                OmniFile file = new OmniFile(volumeId, path);

                if (!FilenameUtils.getExtension(file.getName()).contentEquals("xml")) {

                    // Create any necessary directories
                    file.getParentFile().mkdirs();

                    OutputStream out = file.getOutputStream();

                    OmniFiles.copyFileLeaveInOpen(zis, out);
                    if (DEBUG)
                        LogUtil.log(LogUtil.LogType.OMNI_ZIP, "file created: " + file.getPath());

                    progressStream.putStream("Unpacked: " + entry.getName());
                }
            }
        }
        zis.close();

    } catch (IOException e) {
        LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e);
        return false;
    }

    return true;
}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 * Unzips files to output directory./*from  w w  w . java 2s .c  om*/
 * @param inZip Zip file
 * @param outDir Output directory
 * @throws IOException If an error occurs.
 */
public static void unzip(String inZip, String outDir) throws IOException {

    File sourceZipFile = new File(inZip);
    File unzipDestinationDirectory = new File(outDir);

    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        // System.out.println("Extracting: " + entry);

        File destFile = new File(unzipDestinationDirectory, currentEntry);

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        // extract file if not a directory
        if (!entry.isDirectory()) {
            BufferedInputStream is = null;
            BufferedOutputStream dest = null;
            try {
                is = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[BUFFER];

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

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
            } finally {
                IOUtils.closeQuietly(dest);
                IOUtils.closeQuietly(is);
            }
        }
    }
    zipFile.close();
}

From source file:Main.java

public static boolean unzip(InputStream inputStream, String dest, boolean replaceIfExists) {

    final int BUFFER_SIZE = 4096;

    BufferedOutputStream bufferedOutputStream = null;

    boolean succeed = true;

    try {//from  w  w w.ja v a2s . c  o  m
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {

            String zipEntryName = zipEntry.getName();

            //             if(!zipEntry.isDirectory()) {
            //                 File fil = new File(dest + zipEntryName);
            //                 fil.getParent()
            //             }

            // file exists ? delete ?
            File file2 = new File(dest + zipEntryName);

            if (file2.exists()) {
                if (replaceIfExists) {

                    try {
                        boolean b = deleteDir(file2);
                        if (!b) {
                            Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName);
                        } else {
                            Log.d("Haggle", "Unzip deleted " + dest + zipEntryName);
                        }
                    } catch (Exception e) {
                        Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName, e);
                    }
                }
            }

            // extract
            File file = new File(dest + zipEntryName);

            if (file.exists()) {

            } else {
                if (zipEntry.isDirectory()) {
                    file.mkdirs();
                    chmod(file, 0755);

                } else {

                    // create parent file folder if not exists yet
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                        chmod(file.getParentFile(), 0755);
                    }

                    byte buffer[] = new byte[BUFFER_SIZE];
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
                    int count;

                    while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                        bufferedOutputStream.write(buffer, 0, count);
                    }

                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
            }

            // enable standalone python
            if (file.getName().endsWith(".so") || file.getName().endsWith(".xml")
                    || file.getName().endsWith(".py") || file.getName().endsWith(".pyc")
                    || file.getName().endsWith(".pyo")) {
                chmod(file, 0755);
            }

            Log.d("Haggle", "Unzip extracted " + dest + zipEntryName);
        }

        zipInputStream.close();

    } catch (FileNotFoundException e) {
        Log.e("Haggle", "Unzip error, file not found", e);
        succeed = false;
    } catch (Exception e) {
        Log.e("Haggle", "Unzip error: ", e);
        succeed = false;
    }

    return succeed;
}

From source file:org.calrissian.restdoclet.writer.swagger.SwaggerWriter.java

private static void copySwagger() throws IOException {
    ZipInputStream swaggerZip = null;
    FileOutputStream out = null;//from  w ww.ja va  2s.c o  m
    try {
        swaggerZip = new ZipInputStream(
                Thread.currentThread().getContextClassLoader().getResourceAsStream(SWAGGER_UI_ARTIFACT));
        ZipEntry entry;
        while ((entry = swaggerZip.getNextEntry()) != null) {
            final File swaggerFile = new File(".", entry.getName());
            if (entry.isDirectory()) {
                if (!swaggerFile.isDirectory() && !swaggerFile.mkdirs()) {
                    throw new RuntimeException("Unable to create directory: " + swaggerFile);
                }
            } else {
                copy(swaggerZip, new FileOutputStream(swaggerFile));
            }
        }
    } finally {
        close(swaggerZip, out);
    }
}

From source file:com.seleniumtests.util.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();

    try (JarFile jar = new JarFile(location);) {
        logger.info("Extracting jar file::: " + location);
        firefoxProfile.mkdir();/*  w  w  w.  ja v a2s.com*/

        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
                try (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:com.seleniumtests.util.FileUtility.java

/**
 * Unzip file to a temp directory//ww  w .java  2  s.  co m
 * @param zippedFile
 * @return the output folder
 * @throws IOException
 */
public static File unzipFile(final File zippedFile) throws IOException {
    File outputFolder = Files.createTempDirectory("tmp").toFile();
    try (ZipFile zipFile = new ZipFile(zippedFile)) {
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final File entryDestination = new File(outputFolder, entry.getName());
            if (entry.isDirectory()) {
                //noinspection ResultOfMethodCallIgnored
                entryDestination.mkdirs();
            } else {
                //noinspection ResultOfMethodCallIgnored
                entryDestination.getParentFile().mkdirs();
                final InputStream in = zipFile.getInputStream(entry);
                final OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    }
    return outputFolder;
}

From source file:pl.betoncraft.betonquest.editor.model.PackageSet.java

public static PackageSet loadFromZip(ZipFile file) throws IOException, PackageNotFoundException {
    HashMap<String, HashMap<String, InputStream>> setMap = new HashMap<>();
    Enumeration<? extends ZipEntry> entries = file.entries();
    String setName = file.getName().substring(file.getName().lastIndexOf(File.separatorChar) + 1)
            .replace(".zip", "");
    // extract correct entries from the zip file
    while (true) {
        try {//  ww w.  j a  va  2s.c  om
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();
            // get the correct path separator (both can be used)
            char separator = (entryName.contains("/") ? '/' : '\\');
            // index of first separator used to get set name
            int index = entryName.indexOf(separator);
            // skip entry if there are no path separators (files in zip root like license, readme etc.)
            if (index < 0) {
                continue;
            }
            if (!entryName.endsWith(".yml")) {
                continue;
            }
            String[] parts = entryName.split(Pattern.quote(String.valueOf(separator)));
            String ymlName = parts[parts.length - 1].substring(0, parts[parts.length - 1].length() - 4);
            StringBuilder builder = new StringBuilder();
            int length = parts.length - 1;
            boolean conversation = false;
            if (parts[length - 1].equals("conversations")) {
                length--;
                conversation = true;
            }
            for (int i = 0; i < length; i++) {
                builder.append(parts[i] + '-');
            }
            String packName = builder.substring(0, builder.length() - 1);
            HashMap<String, InputStream> packMap = setMap.get(packName);
            if (packMap == null) {
                packMap = new HashMap<>();
                setMap.put(packName, packMap);
            }
            List<String> allowedNames = Arrays
                    .asList(new String[] { "main", "events", "conditions", "objectives", "journal", "items" });
            if (conversation) {
                packMap.put("conversations." + ymlName, file.getInputStream(entry));
            } else {
                if (allowedNames.contains(ymlName)) {
                    packMap.put(ymlName, file.getInputStream(entry));
                }
            }
        } catch (NoSuchElementException e) {
            break;
        }
    }
    PackageSet set = parseStreams(setName, setMap);
    BetonQuestEditor.getInstance().getSets().add(set);
    RootController.setPackages(BetonQuestEditor.getInstance().getSets());
    return set;
}