Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Get the name of the entry.

Usage

From source file:net.sourceforge.pmd.it.ZipFileExtractor.java

/**
 * Extracts the given zip file into the tempDir.
 * @param zipPath the zip file to extract
 * @param tempDir the target directory/*from www . jav a2  s  .com*/
 * @throws Exception if any error happens during extraction
 */
public static void extractZipFile(Path zipPath, Path tempDir) throws Exception {
    ZipFile zip = new ZipFile(zipPath.toFile());
    try {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File file = tempDir.resolve(entry.getName()).toFile();
            if (entry.isDirectory()) {
                assertTrue(file.mkdirs());
            } else {
                try (InputStream data = zip.getInputStream(entry);
                        OutputStream fileOut = new FileOutputStream(file);) {
                    IOUtils.copy(data, fileOut);
                }
                if ((entry.getUnixMode() & OWNER_EXECUTABLE) == OWNER_EXECUTABLE) {
                    file.setExecutable(true);
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:net.test.aliyun.oss.ImportShooterData.java

@Override
public void onStart(AppContext appContext) throws Throwable {
    String BasePath = "D:/shooterData/";
    OSSClient client = appContext.getInstance(OSSClient.class);
    String tempPath = appContext.getEnvironment().envVar(Environment.HASOR_TEMP_PATH);
    ///*  w ww  .j  av  a 2s  .co  m*/
    File[] zipPacks = new File(BasePath).listFiles();
    long intCount = 0;
    long size = 0;
    for (File zipfile : zipPacks) {
        String fileName = zipfile.getName();
        fileName = fileName.split("\\.")[0];
        ZipFile zipPack = new ZipFile(zipfile);
        Enumeration<ZipArchiveEntry> enumZip = zipPack.getEntries();
        System.out.println(fileName);
        while (enumZip.hasMoreElements()) {
            ZipArchiveEntry ent = enumZip.nextElement();
            if (ent.isDirectory() == true) {
                continue;
            }
            String itemName = ent.getName();
            //
            //            ObjectMetadata info = this.passInfo(tempPath, zipPack, ent);
            //            info.addUserMetadata("oldFileName", itemName);
            //
            //            String key = fileName + "/" + UUID.randomUUID().toString().replace("-", "") + ".rar";
            //InputStream inStream = zipPack.getInputStream(ent);
            //PutObjectResult res = client.putObject("files-subtitle", key, inStream, info);
            //
            intCount++;
            long itemSize = ent.getSize();
            String stated = String.format("%s-%s/%s\t%s\t%s", intCount, fileName, itemName, itemSize, "");
            System.out.println(stated + " -> " + "");
            size = size + itemSize;
        }
        zipPack.close();
    }
    System.out.println(intCount + "\t" + size);
}

From source file:net.test.aliyun.oss.ImportShooterData.java

private ObjectMetadata passInfo(String tempPath, ZipFile zipPack, ZipArchiveEntry ent) throws IOException {
    ObjectMetadata meta = new ObjectMetadata();
    meta.setContentLength(ent.getSize());
    meta.setContentDisposition(ent.getName() + ".rar");
    return meta;/*  w ww  .  ja v a2 s.  c  o  m*/
}

From source file:net.test.aliyun.z7.DownLoadTest.java

public void doWork() throws Throwable {
    //init task to DB
    System.out.println("do Task " + index + "\t from :" + this.newKey);
    ////from   w ww. j  a va  2s. com
    try {
        OSSObject ossObject = client.getObject("files-subtitle-format-zip", this.newKey);
        InputStream infromOSS = ossObject.getObjectContent();
        ZipArchiveInputStream inStream = new ZipArchiveInputStream(infromOSS, "GBK");
        ZipArchiveEntry entry = null;
        StringBuffer buffer = new StringBuffer();
        while ((entry = inStream.getNextZipEntry()) != null) {
            if (entry.isDirectory())
                continue;
            IOUtils.copy(inStream, new ByteArrayOutputStream());
            buffer.append(entry.getName() + "\n");
        }
        infromOSS.close();
        //
        ObjectMetadata meta = ossObject.getObjectMetadata();
        int res = jdbc.update("update `oss-subtitle` set files=?,size=?,lastTime=now() where oss_key =?",
                buffer.toString(), meta.getContentLength(), newKey);
        System.out.println(this.index + " - Validation ok. -> " + res);
        if (res == 0) {
            res = jdbc.update(
                    "insert into `oss-subtitle` (oss_key,files,ori_name,size,lastTime,doWork) values (?,?,?,?,now(),0)",
                    newKey, buffer.toString(), meta.getContentDisposition(), meta.getContentLength());
        }
        //
    } catch (Throwable e) {
        e.printStackTrace();
        //
        int res = jdbc.update("update `oss-subtitle` set files=null,lastTime=now() where oss_key =?", newKey);
        System.out.println("\t error dump to db -> " + res);
    }
}

From source file:net.test.aliyun.z7.Task.java

public void doWork() throws Throwable {
    //init task to DB
    System.out.println("do Task " + index + "\t from :" + oldKey);
    ////from   ww w . ja  v  a  2  s  .  c  om
    //1. 
    System.out.print("\t save to Local -> working... ");
    OSSObject ossObject = client.getObject("files-subtitle", oldKey);
    File rarFile = new File(this.tempPath, ossObject.getObjectMetadata().getContentDisposition());
    rarFile.getParentFile().mkdirs();
    FileOutputStream fos = new FileOutputStream(rarFile, false);
    InputStream inStream = ossObject.getObjectContent();
    IOUtils.copy(inStream, fos);
    fos.flush();
    fos.close();
    System.out.print("-> finish.\n");
    //
    //2.
    System.out.print("\t extract rar -> working... ");
    String extToosHome = "C:\\Program Files (x86)\\7-Zip";
    String rarFileStr = rarFile.getAbsolutePath();
    String toDir = rarFileStr.substring(0, rarFileStr.length() - ".rar".length());
    //
    //
    int extract = Zip7Object.extract(extToosHome, rarFile.getAbsolutePath(), toDir);
    if (extract != 0) {
        if (extract != 2)
            System.out.println();
        FileUtils.deleteDir(new File(toDir));
        rarFile.delete();
        throw new Exception("extract error.");
    }
    System.out.print("-> finish.\n");
    //
    //3.
    System.out.print("\t package zip-> working... ");
    String zipFileName = rarFile.getAbsolutePath();
    zipFileName = zipFileName.substring(0, zipFileName.length() - ".rar".length()) + ".zip";
    ZipArchiveOutputStream outStream = new ZipArchiveOutputStream(new File(zipFileName));
    outStream.setEncoding("GBK");
    Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(),
            FileFilterUtils.directoryFileFilter());
    StringBuffer buffer = new StringBuffer();
    while (itFile.hasNext()) {
        File it = itFile.next();
        if (it.isDirectory())
            continue;
        String entName = it.getAbsolutePath().substring(toDir.length() + 1);
        ZipArchiveEntry ent = new ZipArchiveEntry(it, entName);
        outStream.putArchiveEntry(ent);
        InputStream itInStream = new FileInputStream(it);
        IOUtils.copy(itInStream, outStream);
        itInStream.close();
        outStream.flush();
        outStream.closeArchiveEntry();
        buffer.append(ent.getName());
    }
    outStream.flush();
    outStream.close();
    System.out.print("-> finish.\n");
    //
    //4.
    FileUtils.deleteDir(new File(toDir));
    System.out.print("\t delete temp dir -> finish.\n");
    //
    //5.save to
    System.out.print("\t save to oss -> working... ");
    ObjectMetadata omd = ossObject.getObjectMetadata();
    String contentDisposition = omd.getContentDisposition();
    contentDisposition = contentDisposition.substring(0, contentDisposition.length() - ".rar".length())
            + ".zip";
    omd.setContentDisposition(contentDisposition);
    omd.setContentLength(new File(zipFileName).length());
    InputStream zipInStream = new FileInputStream(zipFileName);
    PutObjectResult result = client.putObject("files-subtitle-format-zip", newKey, zipInStream, omd);
    zipInStream.close();
    new File(zipFileName).delete();
    System.out.print("-> OK:" + result.getETag());
    System.out.print("-> finish.\n");
    //
    //6.save files info
    int res = jdbc.update("update `oss-subtitle` set files=? , size=? , lastTime=now() where oss_key =?",
            buffer.toString(), omd.getContentLength(), newKey);
    System.out.println("\t save info to db -> " + res);
}

From source file:nz.co.kakariki.networkutils.reader.ExtractArchive.java

/**
 * Top unzip method.//from ww  w .j a v  a 2 s .  c  o m
 */
protected static void unzip(File zipfile) throws FileNotFoundException {
    File path = zipfile.getParentFile();
    try {
        ZipArchiveInputStream zais = new ZipArchiveInputStream(new FileInputStream(zipfile));
        ZipArchiveEntry z1 = null;
        while ((z1 = zais.getNextZipEntry()) != null) {
            String fn = z1.getName();
            if (fn.contains("/")) {
                fn = fn.substring(z1.getName().lastIndexOf("/"));
            }
            File f = new File(path + File.separator + fn);
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            int n = 0;
            byte[] content = new byte[BUFFER];
            while (-1 != (n = zais.read(content))) {
                fos.write(content, 0, n);
            }

            bos.flush();
            bos.close();
            fos.close();
        }

        zais.close();
        zipfile.delete();
    } catch (IOException ioe) {
        jlog.fatal("IO read error :: " + ioe);
    }

}

From source file:org.abysm.onionzip.ZipFileExtractHelper.java

void listZipArchiveEntries() throws IOException {
    ZipFile zipFile = new ZipFile(zipFilename, encoding);
    try {/*from  ww  w  .  jav  a  2  s.  com*/
        System.out.println("Length\tDatetime\tName\tEFS\tUnix Mode");
        for (Enumeration<ZipArchiveEntry> zipArchiveEntryEnumeration = zipFile
                .getEntries(); zipArchiveEntryEnumeration.hasMoreElements();) {
            ZipArchiveEntry entry = zipArchiveEntryEnumeration.nextElement();
            System.out.format("%d\t%s\t%s\t%b\t%o\n", entry.getSize(), entry.getLastModifiedDate().toString(),
                    entry.getName(), entry.getGeneralPurposeBit().usesUTF8ForNames(), entry.getUnixMode());
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:org.abysm.onionzip.ZipFileExtractHelper.java

void extractZipArchiveEntries() throws IOException {
    ZipFile zipFile = new ZipFile(zipFilename, encoding);
    try {/*w  w  w. ja  va 2 s  . c  om*/
        for (Enumeration<ZipArchiveEntry> zipArchiveEntryEnumeration = zipFile
                .getEntries(); zipArchiveEntryEnumeration.hasMoreElements();) {
            ZipArchiveEntry entry = zipArchiveEntryEnumeration.nextElement();
            System.out.println(entry.getName());
            if (entry.isDirectory()) {
                Path directory = Paths.get(entry.getName());
                Files.createDirectories(directory);
            } else if (entry.isUnixSymlink()) {
                Path symlink = Paths.get(entry.getName());
                Path parentDirectory = symlink.getParent();
                Path target = Paths.get(zipFile.getUnixSymlink(entry));
                if (parentDirectory != null) {
                    Files.createDirectories(parentDirectory);
                }
                Files.createSymbolicLink(symlink, target);
            } else {
                Path file = Paths.get(entry.getName());
                Path parentDirectory = file.getParent();
                if (parentDirectory != null) {
                    Files.createDirectories(parentDirectory);
                }
                InputStream contentInputStream = zipFile.getInputStream(entry);
                FileOutputStream extractedFileOutputStream = new FileOutputStream(entry.getName());
                try {
                    IOUtils.copy(contentInputStream, extractedFileOutputStream);
                } finally {
                    IOUtils.closeQuietly(contentInputStream);
                    IOUtils.closeQuietly(extractedFileOutputStream);
                }
                FileTime fileTime = FileTime.fromMillis(entry.getLastModifiedDate().getTime());
                Files.setLastModifiedTime(file, fileTime);
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:org.alfresco.repo.action.executer.ImporterActionExecuter.java

/**
 * Extract the file and folder structure of a ZIP file into the specified directory
 * /*from   w  w w . ja va  2  s.  com*/
 * @param archive       The ZIP archive to extract
 * @param extractDir    The directory to extract into
 */
public static void extractFile(ZipFile archive, String extractDir) {
    String fileName;
    String destFileName;
    byte[] buffer = new byte[BUFFER_SIZE];
    extractDir = extractDir + File.separator;
    try {
        for (Enumeration e = archive.getEntries(); e.hasMoreElements();) {
            ZipArchiveEntry entry = (ZipArchiveEntry) e.nextElement();
            if (!entry.isDirectory()) {
                fileName = entry.getName();
                fileName = fileName.replace('/', File.separatorChar);

                if (fileName.startsWith("/") || fileName.indexOf(":" + File.separator) == 1
                        || fileName.contains(".." + File.separator)) {
                    throw new AlfrescoRuntimeException(ARCHIVE_CONTAINS_SUSPICIOUS_PATHS_ERROR);
                }

                destFileName = extractDir + fileName;
                File destFile = new File(destFileName);
                String parent = destFile.getParent();
                if (parent != null) {
                    File parentFile = new File(parent);
                    if (!parentFile.exists())
                        parentFile.mkdirs();
                }
                InputStream in = new BufferedInputStream(archive.getInputStream(entry), BUFFER_SIZE);
                OutputStream out = new BufferedOutputStream(new FileOutputStream(destFileName), BUFFER_SIZE);
                int count;
                while ((count = in.read(buffer)) != -1) {
                    out.write(buffer, 0, count);
                }
                in.close();
                out.close();
            } else {
                File newdir = new File(extractDir + entry.getName());
                newdir.mkdirs();
            }
        }
    } catch (ZipException e) {
        throw new AlfrescoRuntimeException("Failed to process ZIP file.", e);
    } catch (FileNotFoundException e) {
        throw new AlfrescoRuntimeException("Failed to process ZIP file.", e);
    } catch (IOException e) {
        throw new AlfrescoRuntimeException("Failed to process ZIP file.", e);
    }
}

From source file:org.alfresco.repo.content.transform.AppleIWorksContentTransformer.java

@Override
protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options)
        throws Exception {
    final String sourceMimetype = reader.getMimetype();
    final String sourceExtension = getMimetypeService().getExtension(sourceMimetype);
    final String targetMimetype = writer.getMimetype();

    if (log.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Transforming from ").append(sourceMimetype).append(" to ").append(targetMimetype);
        log.debug(msg.toString());//w  ww  .j  a  va2 s. c  om
    }

    ZipArchiveInputStream iWorksZip = null;
    try {
        // iWorks files are zip files (at least in recent versions, iWork 09).
        // If it's not a zip file, the resultant ZipException will be caught as an IOException below.
        iWorksZip = new ZipArchiveInputStream(reader.getContentInputStream());

        ZipArchiveEntry entry = null;
        boolean found = false;
        while (!found && (entry = iWorksZip.getNextZipEntry()) != null) {
            if (MimetypeMap.MIMETYPE_IMAGE_JPEG.equals(targetMimetype)
                    && entry.getName().equals(QUICK_LOOK_THUMBNAIL_JPG)) {
                writer.putContent(iWorksZip);
                found = true;
            } else if (MimetypeMap.MIMETYPE_PDF.equals(targetMimetype)
                    && entry.getName().equals(QUICK_LOOK_PREVIEW_PDF)) {
                writer.putContent(iWorksZip);
                found = true;
            }
        }

        if (!found) {
            throw new AlfrescoRuntimeException(
                    "Unable to transform " + sourceExtension + " file to " + targetMimetype);
        }
    } catch (FileNotFoundException e1) {
        throw new AlfrescoRuntimeException("Unable to transform " + sourceExtension + " file.", e1);
    } catch (IOException e) {
        throw new AlfrescoRuntimeException("Unable to transform " + sourceExtension + " file.", e);
    } finally {
        if (iWorksZip != null) {
            iWorksZip.close();
        }
    }
}