Java Code Examples for java.util.zip.ZipEntry#getName()

The following examples show how to use java.util.zip.ZipEntry#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultArchiveExtractor.java    From flow with Apache License 2.0 6 votes vote down vote up
private void extractZipArchive(File archiveFile, File destinationDirectory)
        throws IOException {
    ZipFile zipFile = new ZipFile(archiveFile);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            final File destPath = new File(
                    destinationDirectory + File.separator + entry
                            .getName());
            prepDestination(destPath, entry.isDirectory());

            copyZipFileContents(zipFile, entry, destPath);
        }
    } finally {
        zipFile.close();
    }
}
 
Example 2
Source File: Install.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void unzip(File zip, File dest) throws IOException {
    Enumeration entries;
    ZipFile zipFile = new ZipFile(zip);

    try {
        entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (entry.isDirectory()) {
                (new File(dest, entry.getName())).mkdirs();
                continue;
            }

            OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(dest, entry.getName())));
            try {
                copyInputStream(zipFile.getInputStream(entry), outputStream);
            } finally {
                outputStream.close();
            }
        }
    } finally {
        zipFile.close();
    }
}
 
Example 3
Source File: ZipUtil.java    From jbake with MIT License 6 votes vote down vote up
/**
 * Extracts content of Zip file to specified output path.
 *
 * @param is             {@link InputStream} InputStream of Zip file
 * @param outputFolder    folder where Zip file should be extracted to
 * @throws IOException    if IOException occurs
 */
public static void extract(InputStream is, File outputFolder) throws IOException {
    ZipInputStream zis = new ZipInputStream(is);
    ZipEntry entry;
    byte[] buffer = new byte[1024];

    while ((entry = zis.getNextEntry()) != null) {
        File outputFile = new File(outputFolder.getCanonicalPath() + File.separatorChar + entry.getName());
        File outputParent = new File(outputFile.getParent());
        outputParent.mkdirs();

        if (entry.isDirectory()) {
            if (!outputFile.exists()) {
                outputFile.mkdir();
            }
        } else {
            try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
            }
        }
    }
}
 
Example 4
Source File: SymbolArchive.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
void addZipEntry(ZipEntry entry) {
    String name = entry.getName();
    if (!name.startsWith(prefix.path)) {
        return;
    }
    name = name.substring(prefix.path.length());
    int i = name.lastIndexOf('/');
    RelativeDirectory dirname = new RelativeDirectory(name.substring(0, i+1));
    String basename = name.substring(i + 1);
    if (basename.length() == 0) {
        return;
    }
    List<String> list = map.get(dirname);
    if (list == null)
        list = List.nil();
    list = list.prepend(basename);
    map.put(dirname, list);
}
 
Example 5
Source File: FileUtils.java    From opensim-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists).
 * http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java
 * @param zipFilePath
 * @param destDirectory
 * @throws IOException
 */
public static void unzip(final Path zipFilePath, final Path destDirectory) throws IOException {
    File destDir = destDirectory.toFile();
    if (!destDir.exists()) {
        destDir.mkdir();
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath.toFile()));
    ZipEntry entry = zipIn.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        String filePath = destDirectory.toString() + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            // if the entry is a file, extracts it
            extractFile(zipIn, filePath);
        } else {
            // if the entry is a directory, make the directory
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}
 
Example 6
Source File: ZipEntryInputStream.java    From marklogic-contentpump with Apache License 2.0 6 votes vote down vote up
public boolean hasNext() {
    try {        
        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            if (entry.getSize() > 0) {
                entryName = entry.getName();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Zip entry name: " + entryName);
                }
                return true;
            }    
        }
        return false;
    } catch (IOException e) {
        LOG.error("Error getting next zip entry from " + fileName, e);
        return false;
    }
}
 
Example 7
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 6 votes vote down vote up
private void extract(ZipFile zipFile, File outputDir) throws IOException
{
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(outputDir,  entry.getName());
        entryDestination.getParentFile().mkdirs();
        if (entry.isDirectory())
            entryDestination.mkdirs();
        else {
            try (InputStream in = zipFile.getInputStream(entry);
                    OutputStream out = Files.newOutputStream(entryDestination.toPath());) {
                org.apache.commons.io.IOUtils.copy(in, out);
            }
        }
    }
}
 
Example 8
Source File: FileUtilities.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Unzips a file all into one directory
 *
 * @param inputStream
 * @param outputFolder
 */
public static void unzip(InputStream inputStream, String outputFolder) {
    byte[] buffer = new byte[1024];
    try {
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }
        ZipInputStream zis = new ZipInputStream(inputStream);
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();
            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }
            fileName = new File(fileName).getName();
            File newFile = new File(outputFolder + SEPARATOR + fileName);
            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();
    } catch (IOException ex) {
    }
}
 
Example 9
Source File: DocumentArchive.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
private void addCursorRow(MatrixCursor cursor, ZipEntry entry) {
    final MatrixCursor.RowBuilder row = cursor.newRow();
    final ParsedDocumentId parsedId = new ParsedDocumentId(mDocumentId, entry.getName());
    row.add(Document.COLUMN_DOCUMENT_ID, parsedId.toDocumentId(mIdDelimiter));

    final File file = new File(entry.getName());
    row.add(Document.COLUMN_DISPLAY_NAME, file.getName());
    row.add(Document.COLUMN_SIZE, entry.getSize());

    final String mimeType = getMimeTypeForEntry(entry);
    row.add(Document.COLUMN_MIME_TYPE, mimeType);

    final int flags = mimeType.startsWith("image/") ? Document.FLAG_SUPPORTS_THUMBNAIL : 0;
    row.add(Document.COLUMN_FLAGS, flags);
}
 
Example 10
Source File: JarFilePackageLister.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void listJarPackages(File jarFile, JarFilePackageListener listener) {
    if (jarFile == null) {
        throw new IllegalArgumentException("jarFile is null!");
    }

    final String jarFileAbsolutePath = jarFile.getAbsolutePath();

    if (!jarFile.exists()) {
        throw new IllegalArgumentException("jarFile doesn't exists! (" + jarFileAbsolutePath + ")");
    }
    if (!jarFile.isFile()) {
        throw new IllegalArgumentException("jarFile is not a file! (" + jarFileAbsolutePath + ")");
    }
    if (!jarFile.getName().endsWith(".jar")) {
        throw new IllegalArgumentException("jarFile is not a jarFile! (" + jarFileAbsolutePath + ")");
    }

    try {
        ZipFile zipFile = new ZipFile(jarFile);
        try {
            final Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();

            while (zipFileEntries.hasMoreElements()) {
                final ZipEntry zipFileEntry = zipFileEntries.nextElement();

                if (zipFileEntry.isDirectory()) {
                    final String zipFileEntryName = zipFileEntry.getName();

                    if (!zipFileEntryName.startsWith("META-INF")) {
                        listener.receivePackage(zipFileEntryName);
                    }
                }
            }
        } finally {
            zipFile.close();
        }
    } catch (IOException e) {
        throw new GradleException("failed to scan jar file for packages (" + jarFileAbsolutePath + ")", e);
    }
}
 
Example 11
Source File: LazyLoadManager.java    From GiraffePlayer2 with Apache License 2.0 5 votes vote down vote up
public static void unZip(File input, File output) throws Exception {
    output.mkdirs();
    ZipInputStream inZip = new ZipInputStream(new FileInputStream(input));
    ZipEntry zipEntry;
    String szName;
    while ((zipEntry = inZip.getNextEntry()) != null) {
        szName = zipEntry.getName();
        if (zipEntry.isDirectory()) {
            // get the folder name of the widget
            szName = szName.substring(0, szName.length() - 1);
            File folder = new File(output.getAbsolutePath() + File.separator + szName);
            folder.mkdirs();
        } else {

            File file = new File(output.getAbsolutePath() + File.separator + szName);
            file.createNewFile();
            // get the output stream of the file
            FileOutputStream out = new FileOutputStream(file);
            int len;
            byte[] buffer = new byte[1024];
            // read (len) bytes into buffer
            while ((len = inZip.read(buffer)) != -1) {
                // write (len) byte from buffer at the position 0
                out.write(buffer, 0, len);
                out.flush();
            }
            out.close();
        }
    }
    inZip.close();
}
 
Example 12
Source File: Processor.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
private String getName(final ZipEntry ze) {
  String name = ze.getName();
  if (isClassEntry(ze)) {
    if (inRepresentation != BYTECODE && outRepresentation == BYTECODE) {
      name = name.substring(0, name.length() - 4); // .class.xml to
      // .class
    } else if (inRepresentation == BYTECODE && outRepresentation != BYTECODE) {
      name += ".xml"; // .class to .class.xml
    }
    // } else if( CODE2ASM.equals( command)) {
    // name = name.substring( 0, name.length()-6).concat( ".asm");
  }
  return name;
}
 
Example 13
Source File: BackupStorage.java    From EagleFactions with MIT License 5 votes vote down vote up
public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
    File destFile = new File(destinationDir, zipEntry.getName());

    String destDirPath = destinationDir.getCanonicalPath();
    String destFilePath = destFile.getCanonicalPath();

    if (!destFilePath.startsWith(destDirPath + File.separator)) {
        throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
    }

    return destFile;
}
 
Example 14
Source File: ZipUtils.java    From panda with Apache License 2.0 5 votes vote down vote up
public static void extract(ZipInputStream zip, File target) throws IOException {
    try {
        ZipEntry entry;

        while ((entry = zip.getNextEntry()) != null) {
            File file = new File(target, entry.getName());

            if (!file.toPath().normalize().startsWith(target.toPath())) {
                throw new IOException("Bad zip entry");
            }

            if (entry.isDirectory()) {
                file.mkdirs();
                continue;
            }

            byte[] buffer = new byte[BUFFER_SIZE];
            file.getParentFile().mkdirs();
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            int count;

            while ((count = zip.read(buffer)) != -1) {
                out.write(buffer, 0, count);
            }

            out.close();
        }
    } finally {
        zip.close();
    }
}
 
Example 15
Source File: ZipUtil.java    From xnx3 with Apache License 2.0 5 votes vote down vote up
private static void unzip(ZipInputStream zis, String basePath) throws IOException {
        ZipEntry entry = zis.getNextEntry();
        if (entry != null) {
//            File file = new File(basePath + File.separator + entry.getName());
            File file = new File(basePath + entry.getName());
            if (file.isDirectory()) {
                // 可能存在空文件夹
                if (!file.exists())
                    file.mkdirs();
                unzip(zis, basePath);
            } else {
                File parentFile = file.getParentFile();
                if (parentFile != null && !parentFile.exists())
                    parentFile.mkdirs();
                FileOutputStream fos = new FileOutputStream(file);// 输出流创建文件时必须保证父路径存在
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = zis.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();
                fos.close();
                zis.closeEntry();
                unzip(zis, basePath);
            }
        }
    }
 
Example 16
Source File: ClassfileBytecodeProviderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test() {
    RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class);
    Providers providers = rt.getHostBackend().getProviders();
    MetaAccessProvider metaAccess = providers.getMetaAccess();

    Assume.assumeTrue(VerifyPhase.class.desiredAssertionStatus());

    String propertyName = Java8OrEarlier ? "sun.boot.class.path" : "jdk.module.path";
    String bootclasspath = System.getProperty(propertyName);
    Assert.assertNotNull("Cannot find value of " + propertyName, bootclasspath);

    for (String path : bootclasspath.split(File.pathSeparator)) {
        if (shouldProcess(path)) {
            try {
                final ZipFile zipFile = new ZipFile(new File(path));
                for (final Enumeration<? extends ZipEntry> entry = zipFile.entries(); entry.hasMoreElements();) {
                    final ZipEntry zipEntry = entry.nextElement();
                    String name = zipEntry.getName();
                    if (name.endsWith(".class") && !name.equals("module-info.class")) {
                        String className = name.substring(0, name.length() - ".class".length()).replace('/', '.');
                        try {
                            checkClass(metaAccess, getSnippetReflection(), className);
                        } catch (ClassNotFoundException e) {
                            throw new AssertionError(e);
                        }
                    }
                }
            } catch (IOException ex) {
                Assert.fail(ex.toString());
            }
        }
    }
}
 
Example 17
Source File: ScanManagerByteCode.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
private void scanForJarClasses(Path path,
                               String packagePath,
                               ByteCodeClassScanner classScanner,
                               JarByteCodeMatcher matcher)
{
  /*
  if (isNullScanPath(path)) {
    return;
  }
  */
  
  //ZipFile zipFile = null;
  //Jar jar = JarPath.create(path).getJar();

  try (InputStream fIs = Files.newInputStream(path)) {
    try (ZipInputStream zIs = new ZipInputStream(fIs)) { 
      ZipEntry entry;

      while ((entry = zIs.getNextEntry()) != null) {
        String entryName = entry.getName();
      
        if (! entryName.endsWith(".class")) {
          continue;
        }

        if (packagePath != null && ! entryName.startsWith(packagePath)) {
          continue;
        }
        
        String subPath = entryName;
        
        subPath = subPath.substring(0, subPath.length() - ".class".length());
        String className = subPath.replace('/', '.');
        
        if (className.startsWith("java.") || className.startsWith("javax.")) {
          continue;
        }
        
        if (! matcher.isClassNameMatch(className)) {
          continue;
        }
        
        matcher.init(); // path, path);
        
        try (InputStream isEntry = new InputStreamEntry(zIs)) {
          try (ReadStream is = new ReadStream(isEntry)) {
            classScanner.init(entryName, is, matcher);

            classScanner.scan();
          }
        }
      }
    }
  } catch (IOException e) {
    log.log(Level.FINE, e.toString(), e);
    System.out.println("IOE: " + e);
    e.printStackTrace();
  }
}
 
Example 18
Source File: ExtractZip.java    From opentest with MIT License 4 votes vote down vote up
@Override
public void run() {
    super.run();

    String sourceFile = this.readStringArgument("sourceFile");
    String targetFolderName = this.readStringArgument("targetFolder");
    Boolean overwrite = this.readBooleanArgument("overwrite", false);

    byte[] buffer = new byte[3072];

    try {
        File targetFolder = new File(targetFolderName);
        if (!targetFolder.isAbsolute()) {
            targetFolder = this.getActor().getTempDir();
        }

        // Make sure target folder exists
        targetFolder.mkdirs();

        ZipInputStream zipInputStream
                = new ZipInputStream(new FileInputStream(sourceFile));

        ZipEntry zipEntry = zipInputStream.getNextEntry();

        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            File newFile = Paths.get(targetFolderName, fileName).toFile();

            if (newFile.exists() && !overwrite) {
                throw new RuntimeException(String.format(
                        "File %s already exists. If you want to overwrite existing  files, please set the \"overwrite\" argument to true.",
                        newFile));
            }

            log.trace(String.format("Extracting ZIP entry into file  %s...", newFile.getAbsoluteFile()));

            // Make sure parent folder for the current entry exists
            newFile.getParentFile().mkdirs();

            FileOutputStream entryOutputStream = new FileOutputStream(newFile);

            int bytesRead;
            while ((bytesRead = zipInputStream.read(buffer)) > 0) {
                entryOutputStream.write(buffer, 0, bytesRead);
            }

            entryOutputStream.close();
            zipEntry = zipInputStream.getNextEntry();
        }

        zipInputStream.closeEntry();
        zipInputStream.close();
        
        this.writeArgument("targetFolder", targetFolder.getAbsolutePath());
    } catch (Exception ex) {
        throw new RuntimeException(String.format(
                "Failed to extract ZIP file %s into folder %s",
                sourceFile,
                targetFolderName), ex);
    }
}
 
Example 19
Source File: ZipUtils.java    From MyUtil with Apache License 2.0 4 votes vote down vote up
/**
 * 解压
 * @param zipFilePath 压缩文件
 * @param unzipPath 解压路径
 * @return return true if success
 */
public static boolean unzip(String zipFilePath, String unzipPath) {
    try{
        ZipFile zipFile = new ZipFile(zipFilePath);
        Enumeration emu = zipFile.entries();
        int i = 0;
        while(emu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry)emu.nextElement();
            if(entry.isDirectory()) {
                new File(unzipPath + "/" + entry.getName()).mkdirs();
                continue;
            }

            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(unzipPath + "/" + entry.getName());
            File parent = file.getParentFile();
            if(parent != null && (!parent.exists())) {
                parent.mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            int count;
            byte data[] = new byte[BUFF_SIZE];
            while((count = bis.read(data, 0, BUFF_SIZE)) != -1) {
                bos.write(data, 0, count);
            }

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

        zipFile.close();

        return true;
    }
    catch (Exception e) {
        Log.e("ZipUtil", "unzip error! zip file:" + zipFilePath + " unzip to path:" + unzipPath);
        e.printStackTrace();
        return false;
    }
}
 
Example 20
Source File: Zip.java    From DexEncryptionDecryption with Apache License 2.0 4 votes vote down vote up
/**
 * 解压zip文件至dir目录
 * @param zip
 * @param dir
 */
public static void unZip(File zip, File dir) {
    try {
        deleteFile(dir);
        ZipFile zipFile = new ZipFile(zip);
        //zip文件中每一个条目
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        //遍历
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            //zip中 文件/目录名
            String name = zipEntry.getName();
            //原来的签名文件 不需要了
            if (name.equals("META-INF/CERT.RSA") || name.equals("META-INF/CERT.SF") || name
                    .equals("META-INF/MANIFEST.MF")) {
                continue;
            }
            //空目录不管
            if (!zipEntry.isDirectory()) {
                File file = new File(dir, name);
                //创建目录
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                //写文件
                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = zipFile.getInputStream(zipEntry);
                byte[] buffer = new byte[2048];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            }
        }
        zipFile.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}