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.android.tradefed.util.FileUtil.java

/**
 * Utility method to extract entire contents of zip file into given
 * directory/*  www.j  av a2s  .c o m*/
 *
 * @param zipFile
 *            the {@link ZipFile} to extract
 * @param destDir
 *            the local dir to extract file to
 * @throws IOException
 *             if failed to extract file
 */
public static void extractZip(ZipFile zipFile, File destDir) throws IOException {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {

        ZipEntry entry = entries.nextElement();
        File childFile = new File(destDir, entry.getName());
        childFile.getParentFile().mkdirs();
        if (entry.isDirectory()) {
            continue;
        } else {
            FileUtil.writeToFile(zipFile.getInputStream(entry), childFile);
        }
    }
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Unzip this file into the given directory. If the zipFile is called "zipFile.zip",
 * the files will be placed into "targetDir/zipFile".
 * @param zipFile/*from  w  w w .  j av  a  2s.c o m*/
 * @param targetDir
 */
public static void unzipFileIntoDirectory(File zipFile, File targetDir) {
    try {
        LOGGER.debug("Expanding Genji extension file " + zipFile.getName());
        int BUFFER = 2048;
        File file = zipFile;
        ZipFile zip = new ZipFile(file);
        String newPath = targetDir + File.separator
                + zipFile.getName().substring(0, zipFile.getName().length() - 4);
        new File(newPath).mkdir();
        Enumeration zipFileEntries = zip.entries();
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(newPath, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();
            // create the parent directory structure if needed
            destinationParent.mkdirs();
            if (!entry.isDirectory()) {
                BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];
                // write the current file to disk
                LOGGER.debug("Unzipping " + destFile.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream 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);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.thoughtworks.go.util.validators.ZipValidator.java

private String nonRootedEntryName(ZipEntry entry) {
    String entryName = entry.getName();
    if (entryName.startsWith("/")) {
        entryName = entryName.substring(1);
    }//from   ww  w  . j  a  v a 2 s  .  c  o m
    return entryName;
}

From source file:ch.ivyteam.ivy.maven.engine.TestClasspathJar.java

@Test
public void readWriteClasspath() throws IOException {
    File jarFile = Files.createTempFile("my", ".jar").toFile();
    ClasspathJar jar = new ClasspathJar(jarFile);
    File content = Files.createTempFile("content", ".jar").toFile();
    jar.createFileEntries(Arrays.asList(content));

    assertThat(jar.getClasspathFiles()).contains(content.getName());

    ZipInputStream jarStream = new ZipInputStream(new FileInputStream(jarFile));
    ZipEntry first = jarStream.getNextEntry();
    assertThat(first.getName()).isEqualTo("META-INF/MANIFEST.MF");
    String manifest = IOUtils.toString(jarStream);
    assertThat(manifest)//from  w  w  w. j a  v  a  2 s  .co  m
            .as("Manifest should not start with a whitespace or it will not be interpreted by the JVM")
            .startsWith("Manifest-Version:");
}

From source file:edu.stanford.epadd.launcher.Splash.java

private static void copyResourcesRecursively(String sourceDirectory, String writeDirectory) throws IOException {
    final URL dirURL = ePADD.class.getClassLoader().getResource(sourceDirectory);
    //final String path = sourceDirectory.substring( 1 );

    if ((dirURL != null) && dirURL.getProtocol().equals("jar")) {
        final JarURLConnection jarConnection = (JarURLConnection) dirURL.openConnection();
        //System.out.println( "jarConnection is " + jarConnection );

        final ZipFile jar = jarConnection.getJarFile();

        final Enumeration<? extends ZipEntry> entries = jar.entries(); // gives ALL entries in jar

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final String name = entry.getName();
            // System.out.println( name );
            if (!name.startsWith(sourceDirectory)) {
                // entry in wrong subdir -- don't copy
                continue;
            }/*  w  w  w  .j  a va2 s  .  c o  m*/
            final String entryTail = name.substring(sourceDirectory.length());

            final File f = new File(writeDirectory + File.separator + entryTail);
            if (entry.isDirectory()) {
                // if its a directory, create it
                final boolean bMade = f.mkdir();
                System.out.println((bMade ? "  creating " : "  unable to create ") + name);
            } else {
                System.out.println("  writing  " + name);
                final InputStream is = jar.getInputStream(entry);
                final OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
                final byte buffer[] = new byte[4096];
                int readCount;
                // write contents of 'is' to 'os'
                while ((readCount = is.read(buffer)) > 0) {
                    os.write(buffer, 0, readCount);
                }
                os.close();
                is.close();
            }
        }

    } else if (dirURL == null) {
        throw new IllegalStateException("can't find " + sourceDirectory + " on the classpath");
    } else {
        // not a "jar" protocol URL
        throw new IllegalStateException("don't know how to handle extracting from " + dirURL);
    }
}

From source file:com.openkm.misc.ZipTest.java

public void testJava() throws IOException {
    log.debug("testJava()");
    File zip = File.createTempFile("java_", ".zip");

    // Create zip
    FileOutputStream fos = new FileOutputStream(zip);
    ZipOutputStream zos = new ZipOutputStream(fos);
    zos.putNextEntry(new ZipEntry("coeta"));
    zos.closeEntry();//from  w  ww  .j  a  v a  2  s .co  m
    zos.close();

    // Read zip
    FileInputStream fis = new FileInputStream(zip);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ze = zis.getNextEntry();
    System.out.println(ze.getName());
    assertEquals(ze.getName(), "coeta");
    zis.close();
}

From source file:JarResources.java

public JarResources(String jarFileName) throws Exception {
    this.jarFileName = jarFileName;
    ZipFile zf = new ZipFile(jarFileName);
    Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();

        htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
    }//from   w  w w . j  a va2  s.co m
    zf.close();

    // extract resources and put them into the hashtable.
    FileInputStream fis = new FileInputStream(jarFileName);
    BufferedInputStream bis = new BufferedInputStream(fis);
    ZipInputStream zis = new ZipInputStream(bis);
    ZipEntry ze = null;
    while ((ze = zis.getNextEntry()) != null) {
        if (ze.isDirectory()) {
            continue;
        }

        int size = (int) ze.getSize();
        // -1 means unknown size.
        if (size == -1) {
            size = ((Integer) htSizes.get(ze.getName())).intValue();
        }

        byte[] b = new byte[(int) size];
        int rb = 0;
        int chunk = 0;
        while (((int) size - rb) > 0) {
            chunk = zis.read(b, rb, (int) size - rb);
            if (chunk == -1) {
                break;
            }
            rb += chunk;
        }

        htJarContents.put(ze.getName(), b);
    }
}

From source file:com.geocent.owf.openlayers.handler.KmzHandler.java

@Override
public String handleContent(HttpServletResponse response, InputStream responseStream) throws IOException {
    ZipInputStream zis = new ZipInputStream(responseStream);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];

    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        if (ze.getName().endsWith("kml")) {
            int len;
            while ((len = zis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }/*  w w  w.ja v a  2 s.  c om*/

            response.setContentType(ContentTypes.KML.getContentType());
            return new String(baos.toByteArray(), Charset.defaultCharset());
        }

        ze = zis.getNextEntry();
    }

    throw new IOException("Missing KML file entry.");
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

/**
 * copy guidelines from the exported project
 * @param zip the ZIP file.//w w  w .  j a va2s  .com
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createProjectGuideline(ZipFile zip, Project aProject, RepositoryService aRepository)
        throws IOException {
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
        String entryName = normalizeEntryName(entry);

        if (entryName.startsWith(GUIDELINE)) {
            String filename = FilenameUtils.getName(entry.getName());
            File guidelineDir = aRepository.getGuidelinesFile(aProject);
            FileUtils.forceMkdir(guidelineDir);
            FileUtils.copyInputStreamToFile(zip.getInputStream(entry), new File(guidelineDir, filename));

            LOG.info("Imported guideline [" + filename + "] for project [" + aProject.getName() + "] with id ["
                    + aProject.getId() + "]");
        }
    }
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Gets the names of all the subclasses from a jar which extend (implement) a superclass (interface).
 * It does not deal with packages, it tries to find all such classes within the jar
 * Sometimes it is not enough to find the classes in a package because:
 *    1.   The subclasses are not necessary in the same package as the superclass
 *    2.   When the same package exists in two or more jar files then only the first jar is found (by URL)
 * @param file the jar file//from   ww  w. ja  v  a2s.c o m
 * @param superclass
  * @param constructorClasses
  * @param constructorParameters
 * @return
 */
private static List<String> getSubclassesFromJarInLib(File file, Class superclass, Class[] constructorClasses,
        Object[] constructorParameters) {
    List<String> classes = new ArrayList<String>();
    Object o;
    if (file == null || !file.exists() || superclass == null) {
        return classes;
    }
    JarFile jfile = null;
    try {
        jfile = new JarFile(file);
    } catch (IOException e1) {
    }
    if (jfile != null) {
        LOGGER.debug("Searching in " + file.getName());
        try {
            Enumeration e = jfile.entries();
            while (e.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                String entryname = entry.getName();
                if (//entryname.startsWith(starts) &&
                    //(entryname.lastIndexOf('/')<=starts.length()) &&
                entryname.endsWith(".class")) {
                    String classname = entryname.substring(0, entryname.length() - 6);
                    if (classname.startsWith("/")) {
                        classname = classname.substring(1);
                    }
                    classname = classname.replace('/', '.');
                    try {
                        // Try to create an instance of the object
                        Class c = null;
                        try {
                            c = Class.forName(classname);
                        } catch (Exception classByName) {
                            LOGGER.debug(
                                    "Finding a class by name " + classname + " failed with " + classByName);
                        }
                        if (c != null) {
                            o = null;
                            if (constructorClasses == null || constructorClasses.length == 0) {
                                //default constructor
                                o = c.newInstance();
                            } else {
                                //probably lucene analyzers with Version
                                Constructor ct = null;
                                try {
                                    ct = c.getConstructor(constructorClasses);
                                } catch (Exception getConst) {
                                    LOGGER.debug(getConst);
                                }
                                if (ct == null) {
                                    //older analyzers (lucene<3)
                                    try {
                                        //default constructor. Some analyzers use default constructor even in lucene 3.0
                                        //(although the corresponding javadoc states it with Version parameter)
                                        o = c.newInstance();
                                    } catch (Exception exception) {
                                    }
                                } else {
                                    try {
                                        if (ct != null) {
                                            o = ct.newInstance(constructorParameters);
                                        }
                                    } catch (Exception callConst) {
                                    }
                                }
                            }
                            if (o != null && superclass.isInstance(o)) {
                                classes.add(classname);
                                LOGGER.debug("Found analizer: " + classname);
                            }
                        }
                    } catch (InstantiationException iex) {
                        // We try to instanciate an interface
                        // or an object that does not have a
                        // default constructor, ignore
                    } catch (IllegalAccessException iaex) {
                        // The class is not public, ignore
                    } catch (Exception ex) {
                        LOGGER.warn("Finding a class in a jar failed with exception " + ex.getMessage());
                    }
                }
            }
        } catch (Exception t) {
            LOGGER.warn("Finding a class in a jar failed with throwable " + t.getMessage());
        }
    }
    return classes;
}