Java Code Examples for org.apache.commons.compress.archivers.zip.ZipArchiveEntry#getName()

The following examples show how to use org.apache.commons.compress.archivers.zip.ZipArchiveEntry#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: ZipUtils.java    From youtubedl-android with GNU General Public License v3.0 6 votes vote down vote up
public static void unzip(InputStream inputStream, File targetDirectory) throws IOException, IllegalAccessException {
    try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new BufferedInputStream(inputStream))) {
        ZipArchiveEntry entry = null;
        while ((entry = zis.getNextZipEntry()) != null) {
            File entryDestination = new File(targetDirectory, entry.getName());
            // prevent zipSlip
            if (!entryDestination.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath() + File.separator)) {
                throw new IllegalAccessException("Entry is outside of the target dir: " + entry.getName());
            }
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                try (OutputStream out = new FileOutputStream(entryDestination)) {
                    IOUtils.copy(zis, out);
                }
            }

        }
    }
}
 
Example 2
Source File: ZipFileIterator.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public InputStream next() {
    ZipArchiveEntry zipEntry = zipEntries.nextElement();

    StopWatch sw = new StopWatch(zipEntry.getName());

    InputStream feStream = null;

    try {
        return zipFile.getInputStream(zipEntry);
    } catch (IOException e) {
        IOUtils.closeQuietly(feStream);

        return null;
    } finally {
        IOUtils.closeQuietly(feStream);

        System.out.print(sw.prettyPrint());
    }
}
 
Example 3
Source File: CompressExample.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
public static void makeOnlyUnZip() throws ArchiveException, IOException{
		final InputStream is = new FileInputStream("D:/中文名字.zip");
		ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP, is);
		ZipArchiveEntry entry = entry = (ZipArchiveEntry) in.getNextEntry();
		
		String dir = "D:/cnname";
		File filedir = new File(dir);
		if(!filedir.exists()){
			filedir.mkdir();
		}
//		OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
		OutputStream out = new FileOutputStream(new File(filedir, entry.getName()));
		IOUtils.copy(in, out);
		out.close();
		in.close();
	}
 
Example 4
Source File: BarFileInstaller.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * barファイルの構造をチェックする.
 */
private boolean checkBarFileStructures(ZipArchiveEntry zae, Map<String, String> requiredBarFiles)
        throws UnsupportedEncodingException, ParseException {

    String entryName = zae.getName(); // ex. "bar/00_meta/00_manifest.json"
    if (requiredBarFiles.containsKey(entryName)) {
        requiredBarFiles.remove(entryName);
    }
    return true;
}
 
Example 5
Source File: ZipUtils.java    From youtubedl-android with GNU General Public License v3.0 5 votes vote down vote up
public static void unzip(File sourceFile, File targetDirectory) throws IOException, ErrnoException, IllegalAccessException {
    try (ZipFile zipFile = new ZipFile(sourceFile)) {
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File entryDestination = new File(targetDirectory, entry.getName());
            // prevent zipSlip
            if (!entryDestination.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath() + File.separator)) {
                throw new IllegalAccessException("Entry is outside of the target dir: " + entry.getName());
            }
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else if (entry.isUnixSymlink()) {
                try (InputStream in = zipFile.getInputStream(entry)) {
                    String symlink = IOUtils.toString(in, StandardCharsets.UTF_8);
                    Os.symlink(symlink, entryDestination.getAbsolutePath());
                }
            } else {
                entryDestination.getParentFile().mkdirs();
                try (InputStream in = zipFile.getInputStream(entry);
                     OutputStream out = new FileOutputStream(entryDestination)) {
                    IOUtils.copy(in, out);
                }
            }
        }
    }
}
 
Example 6
Source File: Zip.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private File unzipEntry(ZipFile zipFile, ZipArchiveEntry entry, Path targetDirectory,
        Consumer<ZipExtractionResult> unzipCallback) {
    final String fileName = entry.getName();
    final long compressedSize = entry.getCompressedSize();

    final Path targetPath = targetDirectory.resolve(fileName);
    try {
        if (entry.isDirectory()) {
            LOGGER.info(String.format("Attempting to create output directory %s.", targetPath.toString()));

            Files.createDirectories(targetPath);
        } else {
            Files.createDirectories(targetPath.getParent());

            try (InputStream in = zipFile.getInputStream(entry)) {
                LOGGER.info(String.format("Creating output file %s.", targetPath.toString()));

                Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);

                // update progress bar
                unzipCallback.accept(new ZipExtractionResult(compressedSize, fileName));
            }
        }

        return targetPath.toFile();
    } catch (IOException e) {
        throw new ArchiveException(String.format("Unable to extract file \"%s\"", fileName), e);
    }
}
 
Example 7
Source File: ZipLeveledStructureProvider.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a new file zip entry with the specified name.
 * @param entry the entry to create the file for
 */
protected void createFile(ZipArchiveEntry entry) {
    IPath pathname = new Path(entry.getName());
    ZipArchiveEntry parent;
    if (pathname.segmentCount() == 1) {
        parent = root;
    } else {
        parent = directoryEntryCache.get(pathname
                .removeLastSegments(1));
    }

    @Nullable List<ZipArchiveEntry> childList = children.get(parent);
    NonNullUtils.checkNotNull(childList).add(entry);
}
 
Example 8
Source File: ScatterZipOutputStream.java    From importer-exporter with Apache License 2.0 5 votes vote down vote up
void addArchiveEntry(ZipArchiveEntry zipArchiveEntry, InputStreamSupplier source) throws IOException {
    try (InputStream payloadStream = source.get()) {
        streamCompressor.deflate(payloadStream, zipArchiveEntry.getMethod());

        String entry = zipArchiveEntry.getName() + "," +
                zipArchiveEntry.getMethod() + "," +
                streamCompressor.getCrc32() + "," +
                streamCompressor.getBytesWrittenForLastEntry() + "," +
                streamCompressor.getBytesRead() + "\n";

        entryStore.writeOut(entry.getBytes(StandardCharsets.UTF_8), 0, entry.length());
    }
}
 
Example 9
Source File: Unzip.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Get a listing of all files in a zip file
 *
 * @param zip The zip file to scan
 * @param relativePath The relative path where the extraction will be rooted
 * @return The list of paths in {@code zip} sorted by path so dirs come before contents.
 */
private static SortedMap<Path, ZipArchiveEntry> getZipFilePaths(
    ZipFile zip, Path relativePath, PatternsMatcher entriesToExclude) {
  SortedMap<Path, ZipArchiveEntry> pathMap = new TreeMap<>();
  for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) {
    String entryName = entry.getName();
    if (entriesToExclude.matches(entryName)) {
      continue;
    }
    Path target = relativePath.resolve(entryName).normalize();
    pathMap.put(target, entry);
  }
  return pathMap;
}
 
Example 10
Source File: MavenDownloader.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
public static void unzip(File zipFile, File destination)
        throws IOException {
    ZipFile zip = new ZipFile(zipFile);
    try {
        Enumeration<ZipArchiveEntry> e = zip.getEntries();
        while (e.hasMoreElements()) {
            ZipArchiveEntry entry = e.nextElement();
            File file = new File(destination, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                InputStream is = zip.getInputStream(entry);
                File parent = file.getParentFile();
                if (parent != null && parent.exists() == false) {
                    parent.mkdirs();
                }
                FileOutputStream os = new FileOutputStream(file);
                try {
                    IOUtils.copy(is, os);
                } finally {
                    os.close();
                    is.close();
                }
                file.setLastModified(entry.getTime());
                int mode = entry.getUnixMode();
                if ((mode & EXEC_MASK) != 0) {
                    if (!file.setExecutable(true)) {
                    }
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zip);
    }
}
 
Example 11
Source File: LocalFileSystemOperations.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
private void extractZip( String zipFilePath, String outputDirPath ) {

        ZipArchiveEntry zipEntry = null;
        File outputDir = new File(outputDirPath);
        outputDir.mkdirs();//check if the dir is created

        try (ZipFile zipFile = new ZipFile(zipFilePath)) {
            Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
            int unixPermissions = 0;

            while (entries.hasMoreElements()) {
                zipEntry = entries.nextElement();
                if (log.isDebugEnabled()) {
                    log.debug("Extracting " + zipEntry.getName());
                }
                File entryDestination = new File(outputDirPath, zipEntry.getName());

                unixPermissions = zipEntry.getUnixMode();
                if (zipEntry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = null;
                    OutputStream out = null;

                    in = zipFile.getInputStream(zipEntry);
                    out = new BufferedOutputStream(new FileOutputStream(entryDestination));

                    IoUtils.copyStream(in, out);
                }
                if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX
                    // set file/dir permissions, after it is created
                    Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(),
                                                  getPosixFilePermission(unixPermissions));
                }
            }
        } catch (Exception e) {
            String errorMsg = "Unable to unzip " + ((zipEntry != null)
                                                    ? zipEntry.getName() + " from "
                                                    : "")
                              + zipFilePath + ".Target directory '" + outputDirPath
                              + "' is in inconsistent state.";
            throw new FileSystemOperationException(errorMsg, e);
        }

    }
 
Example 12
Source File: LocalFileSystemOperations.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Unzip file to local or remote machine. If the machine is UNIX-like it will preserve the permissions
 *
 * @param zipFilePath the zip file path
 * @param outputDirPath output directory. The directory will be created if it does not exist
 * @throws FileSystemOperationException
 */
@Deprecated
@Override
public void unzip(
        String zipFilePath,
        String outputDirPath ) throws FileSystemOperationException {

    ZipArchiveEntry zipEntry = null;
    File outputDir = new File(outputDirPath);
    outputDir.mkdirs();//check if the dir is created

    try (ZipFile zipFile = new ZipFile(zipFilePath)) {
        Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
        int unixPermissions = 0;

        while (entries.hasMoreElements()) {
            zipEntry = entries.nextElement();
            if (log.isDebugEnabled()) {
                log.debug("Extracting " + zipEntry.getName());
            }
            File entryDestination = new File(outputDirPath, zipEntry.getName());

            unixPermissions = zipEntry.getUnixMode();
            if (zipEntry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = null;
                OutputStream out = null;

                in = zipFile.getInputStream(zipEntry);
                out = new BufferedOutputStream(new FileOutputStream(entryDestination));

                IoUtils.copyStream(in, out);
            }
            if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX
                // set file/dir permissions, after it is created
                Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(),
                                              getPosixFilePermission(unixPermissions));
            }
        }
    } catch (Exception e) {
        String errorMsg = "Unable to unzip " + ((zipEntry != null)
                                                ? zipEntry.getName() + " from "
                                                : "")
                          + zipFilePath + ".Target directory '" + outputDirPath
                          + "' is in inconsistent state.";
        throw new FileSystemOperationException(errorMsg, e);
    }
}
 
Example 13
Source File: XZipAntEntryFilter.java    From xjar with Apache License 2.0 4 votes vote down vote up
@Override
protected String toText(ZipArchiveEntry entry) {
    return entry.getName();
}
 
Example 14
Source File: ZipExtractorProvider.java    From appengine-plugins-core with Apache License 2.0 4 votes vote down vote up
@Override
public void extract(Path archive, Path destination, ProgressListener progressListener)
    throws IOException {

  progressListener.start(
      "Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

  String canonicalDestination = destination.toFile().getCanonicalPath();

  // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions
  // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to
  // all the zip file data and will return "0" for any call to getUnixMode().
  try (ZipFile zipFile = new ZipFile(archive.toFile())) {
    // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count);
    Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
    while (zipEntries.hasMoreElements()) {
      ZipArchiveEntry entry = zipEntries.nextElement();
      Path entryTarget = destination.resolve(entry.getName());

      String canonicalTarget = entryTarget.toFile().getCanonicalPath();
      if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
        throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
      }

      progressListener.update(1);
      logger.fine(entryTarget.toString());

      if (entry.isDirectory()) {
        if (!Files.exists(entryTarget)) {
          Files.createDirectories(entryTarget);
        }
      } else {
        if (!Files.exists(entryTarget.getParent())) {
          Files.createDirectories(entryTarget.getParent());
        }
        try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
          try (InputStream in = zipFile.getInputStream(entry)) {
            IOUtils.copy(in, out);
            PosixFileAttributeView attributeView =
                Files.getFileAttributeView(entryTarget, PosixFileAttributeView.class);
            if (attributeView != null) {
              attributeView.setPermissions(
                  PosixUtil.getPosixFilePermissions(entry.getUnixMode()));
            }
          }
        }
      }
    }
  }
  progressListener.done();
}
 
Example 15
Source File: XZipRegexEntryFilter.java    From xjar with Apache License 2.0 4 votes vote down vote up
@Override
protected String toText(ZipArchiveEntry entry) {
    return entry.getName();
}
 
Example 16
Source File: ExtensionUtils.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Unpacks a given zip file to {@link ApplicationLayout#getExtensionInstallationDir}. The 
 * file permissions in the original zip will be retained.
 * <p>
 * Note: This method uses the Apache zip files since they keep track of permissions info; 
 * the built-in java objects (ZipEntry et al.) do not.
 * 
 * @param zipFile the zip file to unpack
 * @param monitor the task monitor
 * @throws ExtensionException if any part of the unzipping fails, or if the target location is invalid
 * @throws CancelledException if the user cancels the unzip
 * @throws IOException if error unzipping zip file
 */
private static void unzipToInstallationFolder(File zipFile, TaskMonitor monitor)
		throws ExtensionException, CancelledException, IOException {

	ApplicationLayout layout = Application.getApplicationLayout();

	if (!isZip(zipFile)) {
		throw new ExtensionException(zipFile.getAbsolutePath() + " is not a valid zip file",
			ExtensionExceptionType.ZIP_ERROR);
	}

	if (layout.getExtensionInstallationDir() == null ||
		!layout.getExtensionInstallationDir().exists()) {
		throw new ExtensionException(
			"Extension installation directory is not valid: " +
				layout.getExtensionInstallationDir(),
			ExtensionExceptionType.INVALID_INSTALL_LOCATION);
	}

	try (ZipFile zFile = new ZipFile(zipFile)) {

		Enumeration<ZipArchiveEntry> entries = zFile.getEntries();
		while (entries.hasMoreElements()) {

			ZipArchiveEntry entry = entries.nextElement();

			String filePath =
				(layout.getExtensionInstallationDir() + File.separator + entry.getName());

			File file = new File(filePath);

			if (entry.isDirectory()) {
				file.mkdirs();
			}
			else {
				try (OutputStream outputStream =
					new BufferedOutputStream(new FileOutputStream(file))) {

					// Create the file at the new location...
					IOUtils.copy(zFile.getInputStream(entry), outputStream);

					// ...and update its permissions. But only continue if the zip
					// was created on a unix platform. If not we cannot use the posix
					// libraries to set permissions. 
					if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_UNIX) {

						int mode = entry.getUnixMode();
						if (mode != 0) { // 0 indicates non-unix platform
							Set<PosixFilePermission> perms = getPermissions(mode);

							try {
								Files.setPosixFilePermissions(file.toPath(), perms);
							}
							catch (UnsupportedOperationException e) {
								// Need to catch this, as Windows does not support the
								// posix call. This is not an error, however, and should
								// just silently fail.
							}
						}
					}
				}
			}
		}
	}
}
 
Example 17
Source File: ZipFileIterator.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
public ZipFileEntry next() {
    ZipArchiveEntry zipEntry = zipEntries.nextElement();

    return new ZipFileEntry(zipFilePath, zipEntry.getName());
}
 
Example 18
Source File: JarUtils.java    From bytecode-viewer with GNU General Public License v3.0 4 votes vote down vote up
public static void put2(final File jarFile) throws IOException
{
    //if this ever fails, worst case import Sun's jarsigner code from JDK 7 re-sign the jar to rebuild the CRC, should also rebuild the archive byte offsets

    FileContainer container = new FileContainer(jarFile);
    HashMap<String, byte[]> files = new HashMap<>();

    Path path = jarFile.toPath();

    String fileBaseName = FilenameUtils.getBaseName(path.getFileName().toString());
    Path destFolderPath = Paths.get(path.getParent().toString(), fileBaseName);

    try (ZipFile zipFile = new ZipFile(jarFile))
    {
        Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements())
        {
            ZipArchiveEntry entry = entries.nextElement();
            Path entryPath = destFolderPath.resolve(entry.getName());
            String name = entry.getName();
            if (entry.isDirectory())
            {
                //directory
            }
            else
            {
                try (InputStream in = zipFile.getInputStream(entry))
                {
                    final byte[] bytes = getBytes(in);

                    if(!name.endsWith(".class"))
                    {
                        files.put(name, bytes);
                    }
                    else
                    {
                        String cafebabe = String.format("%02X", bytes[0]) + String.format("%02X", bytes[1]) + String.format("%02X", bytes[2]) + String.format("%02X", bytes[3]);
                        if (cafebabe.toLowerCase().equals("cafebabe"))
                        {
                            try
                            {
                                final ClassNode cn = getNode(bytes);
                                container.classes.add(cn);
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            files.put(name, bytes);
                        }
                    }

                }
            }
        }
    }

    container.files = files;
    BytecodeViewer.files.add(container);
}
 
Example 19
Source File: ZipArchiveEntryAssert.java    From james-project with Apache License 2.0 4 votes vote down vote up
private static BasicErrorMessageFactory shouldHaveName(ZipArchiveEntry zipArchiveEntry, String expected) {
    return new BasicErrorMessageFactory("%nExpecting %s to have name %s but was %s", zipArchiveEntry, expected, zipArchiveEntry.getName());
}
 
Example 20
Source File: ZipReader.java    From kkFileViewOfficeEdit with Apache License 2.0 4 votes vote down vote up
/**
 * 读取压缩文件
 * 文件压缩到统一目录fileDir下,并且命名使用压缩文件名+文件名因为文件名
 * 可能会重复(在系统中对于同一种类型的材料压缩文件内的文件是一样的,如果文件名
 * 重复,那么这里会被覆盖[同一个压缩文件中的不同目录中的相同文件名暂时不考虑])
 * <b>注:</b>
 * <p>
 *     文件名命名中的参数的说明:
 *     1.archiveName,为避免解压的文件中有重名的文件会彼此覆盖,所以加上了archiveName,因为在ufile中archiveName
 *     是不会重复的。
 *     2.level,这里层级结构的列表我是通过一个map来构造的,map的key是文件的名字,值是对应的文件,这样每次向map中
 *     加入节点的时候都会获取父节点是否存在,存在则会获取父节点的value并将当前节点加入到父节点的childList中(这里利用
 *     的是java语言的引用的特性)。
 * </p>
 * @param filePath
 */
public String readZipFile(String filePath,String fileKey) {
    String archiveSeparator = "/";
    Map<String, FileNode> appender = Maps.newHashMap();
    List imgUrls=Lists.newArrayList();
    String baseUrl= (String) RequestContextHolder.currentRequestAttributes().getAttribute("baseUrl",0);
    String archiveFileName = fileUtils.getFileNameFromPath(filePath);
    try {
        ZipFile zipFile = new ZipFile(filePath, fileUtils.getFileEncodeUTFGBK(filePath));
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        // 排序
        entries = sortZipEntries(entries);
        List<Map<String, ZipArchiveEntry>> entriesToBeExtracted = Lists.newArrayList();
        while (entries.hasMoreElements()){
            ZipArchiveEntry entry = entries.nextElement();
            String fullName = entry.getName();
            int level = fullName.split(archiveSeparator).length;
            // 展示名
            String originName = getLastFileName(fullName, archiveSeparator);
            String childName = level + "_" + originName;
            boolean directory = entry.isDirectory();
            if (!directory) {
                childName = archiveFileName + "_" + originName;
                entriesToBeExtracted.add(Collections.singletonMap(childName, entry));
            }
            String parentName = getLast2FileName(fullName, archiveSeparator, archiveFileName);
            parentName = (level-1) + "_" + parentName;
            FileType type=fileUtils.typeFromUrl(childName);
            if (type.equals(FileType.picture)){//添加图片文件到图片列表
                imgUrls.add(baseUrl+childName);
            }
            FileNode node = new FileNode(originName, childName, parentName, new ArrayList<>(), directory,fileKey);
            addNodes(appender, parentName, node);
            appender.put(childName, node);
        }
        // 开启新的线程处理文件解压
        executors.submit(new ZipExtractorWorker(entriesToBeExtracted, zipFile, filePath));
        fileUtils.setRedisImgUrls(fileKey,imgUrls);
        return new ObjectMapper().writeValueAsString(appender.get(""));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}