Java Code Examples for org.apache.commons.compress.archivers.zip.ZipFile#getEntries()

The following examples show how to use org.apache.commons.compress.archivers.zip.ZipFile#getEntries() . 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: ScrubService.java    From support-diagnostics with Apache License 2.0 6 votes vote down vote up
public Vector<TaskEntry> collectZipEntries(String filename, String scrubDir) {
    Vector<TaskEntry> archiveEntries = new Vector<>();
    try {
        ZipFile zf = new ZipFile(new File(filename));
        Enumeration<ZipArchiveEntry> entries = zf.getEntries();
        ZipArchiveEntry ent = entries.nextElement();
        String archiveName = ent.getName();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zae = entries.nextElement();
            TaskEntry te = new ZipFileTaskEntry(zf, zae, archiveName);
            if(zae.isDirectory()){
                new File(scrubDir + SystemProperties.fileSeparator + te.entryName()).mkdir();
            }
            else{
                archiveEntries.add(te);
            }
        }
    } catch (IOException e) {
        logger.error(Constants.CONSOLE, "Error obtaining zip file entries");
        logger.error(e);
    }

    return archiveEntries;

}
 
Example 2
Source File: ZipUtils.java    From TomboloDigitalConnector with MIT License 6 votes vote down vote up
public static Path unzipToTemporaryDirectory(File file) throws IOException {
    File tempDirectory = new File("/tmp/" + UUID.nameUUIDFromBytes(file.getName().getBytes()).toString());
    if (!tempDirectory.exists()) {
        tempDirectory.mkdir();
        ZipFile zipFile = new ZipFile(file);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            if (!entry.isDirectory()) {
                FileUtils.copyInputStreamToFile(zipFile.getInputStream(entry), new File(Paths.get(tempDirectory.toString(), "/" + entry.getName()).toString()));
            }
        }
        zipFile.close();
    }
    return tempDirectory.toPath();
}
 
Example 3
Source File: CompressExample.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 把一个ZIP文件解压到一个指定的目录中
 * @param zipfilename ZIP文件抽象地址
 * @param outputdir 目录绝对地址
 */
public static void unZipToFolder(String zipfilename, String outputdir) throws IOException {
    File zipfile = new File(zipfilename);
    if (zipfile.exists()) {
        outputdir = outputdir + File.separator;
        FileUtils.forceMkdir(new File(outputdir));

        ZipFile zf = new ZipFile(zipfile, "UTF-8");
        Enumeration zipArchiveEntrys = zf.getEntries();
        while (zipArchiveEntrys.hasMoreElements()) {
            ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();
            if (zipArchiveEntry.isDirectory()) {
                FileUtils.forceMkdir(new File(outputdir + zipArchiveEntry.getName() + File.separator));
            } else {
                IOUtils.copy(zf.getInputStream(zipArchiveEntry), FileUtils.openOutputStream(new File(outputdir + zipArchiveEntry.getName())));
            }
        }
    } else {
        throw new IOException("指定的解压文件不存在:\t" + zipfilename);
    }
}
 
Example 4
Source File: BasicExtractor.java    From embedded-rabbitmq with Apache License 2.0 6 votes vote down vote up
private void extractZip(ZipFile zipFile) {
  Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();
    String fileName = entry.getName();
    File outputFile = new File(config.getExtractionFolder(), fileName);

    if (entry.isDirectory()) {
      makeDirectory(outputFile);
    } else {
      createNewFile(outputFile);
      try {
        InputStream inputStream = zipFile.getInputStream(entry);
        extractFile(inputStream, outputFile, fileName);
      } catch (IOException e) {
        throw new ExtractionException("Error extracting file '" + fileName + "' "
            + "from downloaded file: " + config.getDownloadTarget(), e);
      }
    }
  }
}
 
Example 5
Source File: BarFileValidateTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * barファイル内エントリのファイルサイズ上限値を超えた場合に例外が発生すること.
 */
@Test
public void barファイル内エントリのファイルサイズ上限値を超えた場合に例外が発生すること() {
    TestBarInstaller testBarInstaller = new TestBarInstaller();
    URL fileUrl = ClassLoader.getSystemResource("requestData/barInstall/V1_1_2_bar_minimum.bar");
    File file = new File(fileUrl.getPath());

    try {
        ZipFile zipFile = new ZipFile(file, "UTF-8");
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        long maxBarEntryFileSize = 0;
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zae = entries.nextElement();
            if (zae.isDirectory()) {
                continue;
            }
            testBarInstaller.checkBarFileEntrySize(zae, zae.getName(), maxBarEntryFileSize);
        }
        fail("Unexpected exception");
    } catch (DcCoreException dce) {
        String code = DcCoreException.BarInstall.BAR_FILE_ENTRY_SIZE_TOO_LARGE.getCode();
        assertEquals(code, dce.getCode());
    } catch (Exception ex) {
        fail("Unexpected exception");
    }
}
 
Example 6
Source File: ExtractionTools.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
private static void extractZipFile(final File destination, final ZipFile zipFile) throws IOException {
    final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        final File entryDestination = getDestinationFile(destination, entry.getName());

        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            final InputStream in = zipFile.getInputStream(entry);
            try (final OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}
 
Example 7
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 8
Source File: Mq2Xliff.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 解析 memoQ 的源文件,并将内容拷贝至骨架文件中
 * @param mqZip
 * @param hsSkeleton	R8 hsxliff的骨架文件
 * @throws Exception
 */
private void parseMQZip(String mqZip, String hsSkeleton) throws Exception{
	ZipFile zipFile = new ZipFile(new File(mqZip), "utf-8");
	Enumeration<?> e = zipFile.getEntries();
	byte ch[] = new byte[1024];
	String outputFile = "";
	File mqSklTempFile = File.createTempFile("tempskl", "skl");
	mqSklTempFile.deleteOnExit();
	while (e.hasMoreElements()) {
		ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();
		if ("document.mqxliff".equals(zipEntry.getName())) {
			outputFile = hsSkeleton;
		}else {
			outputFile = mqSklTempFile.getAbsolutePath();
		}
		File zfile = new File(outputFile);
		FileOutputStream fouts = new FileOutputStream(zfile);
		InputStream in = zipFile.getInputStream(zipEntry);
		int i;
		while ((i = in.read(ch)) != -1)
			fouts.write(ch, 0, i);
		fouts.close();
		in.close();
	}
	
	//解析r8骨加文件,并把 mq 的骨架信息添加到 r8 的骨架文件中
	parseHSSkeletonFile();
	copyMqSklToHsSkl(mqSklTempFile);
}
 
Example 9
Source File: Mq2Xliff.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 解析 memoQ 的源文件,并将内容拷贝至骨架文件中
 * @param mqZip
 * @param hsSkeleton	R8 hsxliff的骨架文件
 * @throws Exception
 */
private void parseMQZip(String mqZip, String hsSkeleton) throws Exception{
	ZipFile zipFile = new ZipFile(new File(mqZip), "utf-8");
	Enumeration<?> e = zipFile.getEntries();
	byte ch[] = new byte[1024];
	String outputFile = "";
	File mqSklTempFile = File.createTempFile("tempskl", "skl");
	mqSklTempFile.deleteOnExit();
	while (e.hasMoreElements()) {
		ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();
		if ("document.mqxliff".equals(zipEntry.getName())) {
			outputFile = hsSkeleton;
		}else {
			outputFile = mqSklTempFile.getAbsolutePath();
		}
		File zfile = new File(outputFile);
		FileOutputStream fouts = new FileOutputStream(zfile);
		InputStream in = zipFile.getInputStream(zipEntry);
		int i;
		while ((i = in.read(ch)) != -1)
			fouts.write(ch, 0, i);
		fouts.close();
		in.close();
	}
	
	//解析r8骨加文件,并把 mq 的骨架信息添加到 r8 的骨架文件中
	parseHSSkeletonFile();
	copyMqSklToHsSkl(mqSklTempFile);
}
 
Example 10
Source File: ZipUtil.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
public ZipArchiveEntry readZip(File zipFile, String fileName)
		throws IOException {
	ZipFile zf = new ZipFile(zipFile);
	Enumeration<ZipArchiveEntry> zips = zf.getEntries();
	ZipArchiveEntry zip = null;
	while (zips.hasMoreElements()) {
		zip = zips.nextElement();
		if (fileName.equals(zip.getName())) {
			return zip;
		}
	}
	return null;
}
 
Example 11
Source File: ZipUtil.java    From util with Apache License 2.0 5 votes vote down vote up
/**
 * 功能:得到zip压缩包下的某个文件信息,只能在根目录下查找。
 * @author 朱志杰 QQ:695520848
 * Aug 14, 2013 5:09:49 PM
 * @param zipFile zip压缩文件
 * @param fileName 某个文件名,例如abc.zip下面的a.jpg,需要传入/abc/a.jpg。
 * @return ZipArchiveEntry 压缩文件中的这个文件,没有找到返回null。
 * @throws IOException 文件流异常
 */
public ZipArchiveEntry readZip(File zipFile,String fileName) throws IOException{
	ZipFile zf = new ZipFile(zipFile);
	Enumeration<ZipArchiveEntry> zips=zf.getEntries();
	ZipArchiveEntry zip=null;
	while(zips.hasMoreElements()){
		zip = zips.nextElement();
		if(fileName.equals(zip.getName())){
			return zip;
		}
	}
	return null;
}
 
Example 12
Source File: ZipUtils.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * Unzip archive to given folder.
 *
 * @param archive given archive
 * @param outputDir  given folder
 *
 * @throws IOException in case of error
 */

public void unzipArchive(final File archive, final File outputDir) throws IOException {
    ZipFile zipfile = new ZipFile(archive, encoding);
    for (Enumeration e = zipfile.getEntries(); e.hasMoreElements(); ) {
        final ZipArchiveEntry entry = (ZipArchiveEntry) e.nextElement();
        unzipEntry(zipfile, entry, outputDir);
    }
    zipfile.close();
}
 
Example 13
Source File: ZipUtil.java    From AndroidRobot with Apache License 2.0 4 votes vote down vote up
public Enumeration<ZipArchiveEntry> readZip(File zipFile)
		throws IOException {
	ZipFile zf = new ZipFile(zipFile);
	Enumeration<ZipArchiveEntry> zips = zf.getEntries();
	return zips;
}
 
Example 14
Source File: ZipReader.java    From kkFileView with Apache License 2.0 4 votes vote down vote up
public String readZipFile(String filePath,String fileKey) {
    String archiveSeparator = "/";
    Map<String, FileNode> appender = Maps.newHashMap();
    List<String> imgUrls = Lists.newArrayList();
    String baseUrl = BaseUrlFilter.getBaseUrl();
    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.putImgCache(fileKey,imgUrls);
        return new ObjectMapper().writeValueAsString(appender.get(""));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 15
Source File: WRS2GeometryStore.java    From geowave with Apache License 2.0 4 votes vote down vote up
private void init() throws MalformedURLException, IOException {
  if (!wrs2Shape.exists()) {
    if (!wrs2Directory.delete()) {
      LOGGER.warn("Unable to delete '" + wrs2Directory.getAbsolutePath() + "'");
    }
    final File wsDir = wrs2Directory.getParentFile();
    if (!wsDir.exists() && !wsDir.mkdirs()) {
      LOGGER.warn("Unable to create directory '" + wsDir.getAbsolutePath() + "'");
    }

    if (!wrs2Directory.mkdirs()) {
      LOGGER.warn("Unable to create directory '" + wrs2Directory.getAbsolutePath() + "'");
    }
    // download and unzip the shapefile
    final File targetFile = new File(wrs2Directory, WRS2_SHAPE_ZIP);
    if (targetFile.exists()) {
      if (!targetFile.delete()) {
        LOGGER.warn("Unable to delete file '" + targetFile.getAbsolutePath() + "'");
      }
    }
    FileUtils.copyURLToFile(new URL(WRS2_SHAPE_URL), targetFile);
    final ZipFile zipFile = new ZipFile(targetFile);
    try {
      final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
      while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        if (!entry.isDirectory()) {
          FileUtils.copyInputStreamToFile(
              zipFile.getInputStream(entry),
              new File(wrs2Directory, entry.getName()));
          // HP Fortify "Path Traversal" false positive
          // What Fortify considers "user input" comes only
          // from users with OS-level access anyway
        }
      }
    } finally {
      zipFile.close();
    }
  }
  // read the shapefile and cache the features for quick lookup by path
  // and row
  try {
    final Map<String, Object> map = new HashMap<>();
    map.put("url", wrs2Shape.toURI().toURL());
    final DataStore dataStore = DataStoreFinder.getDataStore(map);
    if (dataStore == null) {
      LOGGER.error("Unable to get a datastore instance, getDataStore returned null");
      return;
    }
    final SimpleFeatureSource source = dataStore.getFeatureSource(WRS2_TYPE_NAME);

    final SimpleFeatureCollection featureCollection = source.getFeatures();
    wrs2Type = featureCollection.getSchema();
    final SimpleFeatureIterator iterator = featureCollection.features();
    while (iterator.hasNext()) {
      final SimpleFeature feature = iterator.next();
      final Number path = (Number) feature.getAttribute("PATH");
      final Number row = (Number) feature.getAttribute("ROW");
      featureCache.put(
          new WRS2Key(path.intValue(), row.intValue()),
          (MultiPolygon) feature.getDefaultGeometry());
    }
  } catch (final IOException e) {
    LOGGER.error(
        "Unable to read wrs2_asc_desc shapefile '" + wrs2Shape.getAbsolutePath() + "'",
        e);
    throw (e);
  }
}
 
Example 16
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;
    }
}
 
Example 17
Source File: ZipUtil.java    From util with Apache License 2.0 2 votes vote down vote up
/**
 * 功能:得到zip压缩包下的所有文件信息。
 * @author 朱志杰 QQ:695520848
 * Aug 14, 2013 5:09:49 PM
 * @param zipFile zip压缩文件
 * @return Enumeration<ZipArchiveEntry> 压缩文件中的文件枚举。
 * @throws IOException 文件流异常
 */
public Enumeration<ZipArchiveEntry> readZip(File zipFile) throws IOException{
	ZipFile zf = new ZipFile(zipFile);
	Enumeration<ZipArchiveEntry> zips=zf.getEntries();
	return zips;
}