Example usage for org.apache.commons.compress.archivers.zip ZipFile getEntry

List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipFile getEntry.

Prototype

public ZipArchiveEntry getEntry(String name) 

Source Link

Document

Returns a named entry - or null if no entry by that name exists.

Usage

From source file:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at
 * the command line.<br>/*  w  ww. ja  v a 2s . c  om*/
 * usage JarPatcher source patch output
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    String patchName = null;
    String outputName = null;
    String sourceName = null;
    if (args.length == 0) {
        System.err.println("usage JarPatcher patch [output [source]]");
        System.exit(1);
    } else {
        patchName = args[0];
        if (args.length > 1) {
            outputName = args[1];
            if (args.length > 2) {
                sourceName = args[2];
            }
        }
    }
    ZipFile patch = new ZipFile(patchName);
    ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list");
    if (listEntry == null) {
        System.err.println("Invalid patch - list entry 'META-INF/file.list' not found");
        System.exit(2);
    }
    BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry)));
    String next = list.readLine();
    if (sourceName == null) {
        sourceName = next;
    }
    next = list.readLine();
    if (outputName == null) {
        outputName = next;
    }
    int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0"));
    int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0"));
    Path sourcePath = Paths.get(sourceName);
    Path outputPath = Paths.get(outputName);
    if (ignoreOutputPaths >= outputPath.getNameCount()) {
        patch.close();
        StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (")
                .append(ignoreOutputPaths).append(" in ").append(outputName).append(")");
        throw new IOException(b.toString());
    }
    if (ignoreSourcePaths >= sourcePath.getNameCount()) {
        patch.close();
        StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (")
                .append(sourcePath).append(" in ").append(sourceName).append(")");
        throw new IOException(b.toString());
    }
    sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount());
    outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount());
    File sourceFile = sourcePath.toFile();
    File outputFile = outputPath.toFile();
    if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs()
            || outputFile.getAbsoluteFile().getParentFile().exists())) {
        patch.close();
        throw new IOException("Failed to create " + outputFile.getAbsolutePath());
    }
    new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile),
            new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list);
    list.close();
}

From source file:com.android.tradefed.util.ZipUtil2.java

/**
 * Utility method to extract one specific file from zip file into a tmp file
 *
 * @param zipFile the {@link ZipFile} to extract
 * @param filePath the filePath of to extract
 * @throws IOException if failed to extract file
 * @return the {@link File} or null if not found
 */// ww  w  .j ava  2s .co m
public static File extractFileFromZip(ZipFile zipFile, String filePath) throws IOException {
    ZipArchiveEntry entry = zipFile.getEntry(filePath);
    if (entry == null) {
        return null;
    }
    File createdFile = FileUtil.createTempFile("extracted", FileUtil.getExtension(filePath));
    FileUtil.writeToFile(zipFile.getInputStream(entry), createdFile);
    applyUnixModeIfNecessary(entry, createdFile);
    return createdFile;
}

From source file:mj.ocraptor.extraction.tika.parser.pkg.ZipContainerDetector.java

private static MediaType detectIWork(ZipFile zip) {
    if (zip.getEntry(IWorkPackageParser.IWORK_COMMON_ENTRY) != null) {
        // Locate the appropriate index file entry, and reads from that
        // the root element of the document. That is used to the identify
        // the correct type of the keynote container.
        for (String entryName : IWorkPackageParser.IWORK_CONTENT_ENTRIES) {
            IWORKDocumentType type = IWORKDocumentType.detectType(zip.getEntry(entryName), zip);
            if (type != null) {
                return type.getType();
            }//from w  ww.ja v a 2 s.  com
        }

        // Not sure, fallback to the container type
        return MediaType.application("vnd.apple.iwork");
    } else {
        return null;
    }
}

From source file:mj.ocraptor.extraction.tika.parser.pkg.ZipContainerDetector.java

private static MediaType detectJar(ZipFile zip) {
    if (zip.getEntry("META-INF/MANIFEST.MF") != null) {
        // It's a Jar file, or something based on Jar

        // Is it an Android APK?
        if (zip.getEntry("AndroidManifest.xml") != null) {
            return MediaType.application("vnd.android.package-archive");
        }/*  w ww. jav a2s .c o m*/

        // Check for WAR and EAR
        if (zip.getEntry("WEB-INF/") != null) {
            return MediaType.application("x-tika-java-web-archive");
        }
        if (zip.getEntry("META-INF/application.xml") != null) {
            return MediaType.application("x-tika-java-enterprise-archive");
        }

        // Looks like a regular Jar Archive
        return MediaType.application("java-archive");
    } else {
        // Some Android APKs miss the default Manifest
        if (zip.getEntry("AndroidManifest.xml") != null) {
            return MediaType.application("vnd.android.package-archive");
        }

        return null;
    }
}

From source file:mj.ocraptor.extraction.tika.parser.pkg.ZipContainerDetector.java

/**
 * OpenDocument files, along with EPub files, have a mimetype
 *  entry in the root of their Zip file. This entry contains the
 *  mimetype of the overall file, stored as a single string.  
 *///from   w ww . j  a v a2s . com
private static MediaType detectOpenDocument(ZipFile zip) {
    try {
        ZipArchiveEntry mimetype = zip.getEntry("mimetype");
        if (mimetype != null) {
            InputStream stream = zip.getInputStream(mimetype);
            try {
                return MediaType.parse(IOUtils.toString(stream, "UTF-8"));
            } finally {
                stream.close();
            }
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}

From source file:mj.ocraptor.extraction.tika.parser.pkg.ZipContainerDetector.java

private static MediaType detectOfficeOpenXML(ZipFile zip, TikaInputStream stream) {
    try {// ww w. j  a  v a2s  .  co m
        if (zip.getEntry("_rels/.rels") != null || zip.getEntry("[Content_Types].xml") != null) {
            // Use POI to open and investigate it for us
            OPCPackage pkg = OPCPackage.open(stream.getFile().getPath(), PackageAccess.READ);
            stream.setOpenContainer(pkg);

            // Detect based on the open OPC Package
            return detectOfficeOpenXML(pkg);
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    } catch (RuntimeException e) {
        return null;
    } catch (InvalidFormatException e) {
        return null;
    }
}

From source file:com.vividsolutions.jump.io.CompressedFile.java

/**
 * Utility file open function - handles compressed and un-compressed files.
 * /*from  w  w  w  .ja v  a  2  s .co  m*/
 * @param filePath
 *          name of the file to search for.
 * @param compressedEntry
 *          name of the compressed file.
 * 
 *          <p>
 *          If compressedEntry = null, opens a FileInputStream on filePath
 *          </p>
 * 
 *          <p>
 *          If filePath ends in ".zip" - opens the compressed Zip and
 *          looks for the file called compressedEntry
 *          </p>
 * 
 *          <p>
 *          If filePath ends in ".gz" - opens the compressed .gz file.
 *          </p>
 */
public static InputStream openFile(String filePath, String compressedEntry) throws IOException {

    System.out.println(filePath + " extract " + compressedEntry);

    if (isTar(filePath)) {
        InputStream is = new BufferedInputStream(new FileInputStream(filePath));
        if (filePath.toLowerCase().endsWith("gz"))
            is = new GzipCompressorInputStream(is, true);
        else if (filePath.matches("(?i).*bz2?"))
            is = new BZip2CompressorInputStream(is, true);
        else if (filePath.matches("(?i).*xz"))
            is = new XZCompressorInputStream(is, true);

        TarArchiveInputStream tis = new TarArchiveInputStream(is);
        if (compressedEntry == null)
            return is;

        TarArchiveEntry entry;
        while ((entry = tis.getNextTarEntry()) != null) {
            if (entry.getName().equals(compressedEntry))
                return tis;
        }

        throw createArchiveFNFE(filePath, compressedEntry);
    }

    else if (compressedEntry == null && isGZip(filePath)) {
        // gz compressed file -- easy
        InputStream is = new BufferedInputStream(new FileInputStream(filePath));
        return new GzipCompressorInputStream(is, true);
    }

    else if (compressedEntry == null && isBZip(filePath)) {
        // bz compressed file -- easy
        InputStream is = new BufferedInputStream(new FileInputStream(filePath));
        return new BZip2CompressorInputStream(is, true);
        //return new org.itadaki.bzip2.BZip2InputStream(is, false);
    }

    else if (compressedEntry == null && isXZ(filePath)) {
        InputStream is = new BufferedInputStream(new FileInputStream(filePath));
        return new XZCompressorInputStream(is, true);
    }

    else if (compressedEntry != null && isZip(filePath)) {

        ZipFile zipFile = new ZipFile(filePath);
        ZipArchiveEntry zipEntry = zipFile.getEntry(compressedEntry);

        if (zipEntry != null)
            return zipFile.getInputStream(zipEntry);

        throw createArchiveFNFE(filePath, compressedEntry);
    }

    else if (compressedEntry != null && isSevenZ(filePath)) {

        SevenZFileGiveStream sevenZFile = new SevenZFileGiveStream(new File(filePath));
        SevenZArchiveEntry entry;
        while ((entry = sevenZFile.getNextEntry()) != null) {
            if (entry.getName().equals(compressedEntry))
                return sevenZFile.getCurrentEntryInputStream();
        }
        throw createArchiveFNFE(filePath, compressedEntry);
    }
    // return plain stream if no compressedEntry
    else if (compressedEntry == null) {
        return new FileInputStream(filePath);
    }

    else {
        throw new IOException("Couldn't determine compressed file type for file '" + filePath
                + "' supposedly containing '" + compressedEntry + "'.");
    }
}

From source file:com.taobao.android.utils.ZipUtils.java

/**
 * zip?//from  w ww  .  ja  v  a2  s  . c  o m
 *
 * @param zipFile
 * @param path
 * @param destFolder
 * @throws IOException
 */
public static File extractZipFileToFolder(File zipFile, String path, File destFolder) {
    ZipFile zip;
    File destFile = null;
    try {
        zip = new ZipFile(zipFile);
        ZipArchiveEntry zipArchiveEntry = zip.getEntry(path);
        if (null != zipArchiveEntry) {
            String name = zipArchiveEntry.getName();
            name = FilenameUtils.getName(name);
            destFile = new File(destFolder, name);
            destFolder.mkdirs();
            destFile.createNewFile();
            InputStream is = zip.getInputStream(zipArchiveEntry);
            FileOutputStream fos = new FileOutputStream(destFile);
            int length = 0;
            byte[] b = new byte[1024];
            while ((length = is.read(b, 0, 1024)) != -1) {
                fos.write(b, 0, length);
            }
            is.close();
            fos.close();
        }
        if (null != zip)
            ZipFile.closeQuietly(zip);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return destFile;
}

From source file:com.taobao.android.tpatch.utils.PatchUtils.java

/**
 * ?so?bundle//from  w  w w . j a v a  2s .  c om
 *
 * @param soFile
 * @return
 */
public static boolean isBundleFile(File soFile) {
    ZipFile zf = null;
    try {
        zf = new ZipFile(soFile);
        Enumeration<ZipArchiveEntry> en = zf.getEntries();
        if (en.hasMoreElements()) {
            for (String name : BUNDLE_FILES) {
                ZipArchiveEntry zipArchiveEntry = zf.getEntry(name);
                if (null == zipArchiveEntry) {
                    return false;
                }

            }
            return true;
        }
        return false;
    } catch (IOException e) {
        return false;
    } finally {
        if (null != zf) {
            try {
                zf.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

/**
 * zip?/*w  w w  . j  av a 2 s.c om*/
 *
 * @param zipFile
 * @param path
 * @param destFolder
 * @throws java.io.IOException
 */
public static File extractZipFileToFolder(File zipFile, String path, File destFolder) {
    ZipFile zip;
    File destFile = null;
    try {
        zip = new ZipFile(zipFile);
        ZipArchiveEntry zipArchiveEntry = zip.getEntry(path);
        if (null != zipArchiveEntry) {
            String name = zipArchiveEntry.getName();
            name = FilenameUtils.getName(name);
            destFile = new File(destFolder, name);
            FileMkUtils.mkdirs(destFolder);
            destFile.createNewFile();
            InputStream is = zip.getInputStream(zipArchiveEntry);
            FileOutputStream fos = new FileOutputStream(destFile);
            int length = 0;
            byte[] b = new byte[1024];
            while ((length = is.read(b, 0, 1024)) != -1) {
                fos.write(b, 0, length);
            }
            is.close();
            fos.close();
        }
        if (null != zip) {
            ZipFile.closeQuietly(zip);
        }
    } catch (IOException e) {
        throw new GradleException(e.getMessage(), e);
    }
    return destFile;
}