在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

使用Java 8的Stream API列出ZIP文件中的条目

2016-12-13 12:56| 发布者: zhangjf| 查看: 527| 评论: 0

摘要: Java 8中的java.util.zip.ZipFile包中提供了stream方法,能够非常容易的获取ZIP压缩包中的条目。在这篇文章中,我会通过一系列的示例来展示我们可以非常快速的遍历ZIP文件中的条目。 注意:为了在这篇博客中做演示 ...
Java 8中的java.util.zip.ZipFile包中提供了stream方法,能够非常容易的获取ZIP压缩包中的条目。在这篇文章中,我会通过一系列的示例来展示我们可以非常快速的遍历ZIP文件中的条目。

注意:为了在这篇博客中做演示,我从GitHub上以ZIP文件的形式下载了我的一个项目,放在了c:/tmp目录下。

Java7之前的做法

在Java7之前,读取一个ZIP文件中的条目的做法,恩……需要一点点小技巧。当你看到下面的代码的时候,大概就会开始有点讨厌Java了。

  1. public class Zipper {
  2. public void printEntries(PrintStream stream, String zip) {
  3. ZipFile zipFile = null;
  4. try {
  5. zipFile = new ZipFile(zip);
  6. Enumeration<? extends ZipEntry> entries = zipFile.entries();
  7. while (entries.hasMoreElements()) {
  8. ZipEntry zipEntry = entries.nextElement();
  9. stream.println(zipEntry.getName());
  10. }
  11. } catch (IOException e) {
  12. // error while opening a ZIP file
  13. } finally {
  14. if (zipFile != null) {
  15. try {
  16. zipFile.close();
  17. } catch (IOException e) {
  18. // do something
  19. }
  20. }
  21. }
  22. }
  23. }
复制代码
Java 7的做法

多谢有了try-with-resources这样新的try代码块的写法,在Java 7中的代码变得稍微好了一些,但我们还是被“强迫”来使用Enumeration来遍历ZIP压缩包中的条目:

  1. public class Zipper {
  2. public void printEntries(PrintStream stream, String zip) {
  3. try (ZipFile zipFile = new ZipFile(zip)) {
  4. Enumeration<? extends ZipEntry> entries = zipFile.entries();
  5. while (entries.hasMoreElements()) {
  6. ZipEntry zipEntry = entries.nextElement();
  7. stream.println(zipEntry.getName());
  8. }
  9. } catch (IOException e) {
  10. // error while opening a ZIP file
  11. }
  12. }
  13. }
复制代码
使用Strean API

真正有意思的是从Java 8开始,Java 8提供在java.util.zip.ZipFile包中提供新的stream方法,能够返回ZIP压缩包中的条目的有序的流,使得Java在处理ZIP压缩包时有了更多的选择。前文提到的读取压缩包的条目的代码可以改写成如下简单的形式:

  1. public class Zipper {
  2. public void printEntries(PrintStream stream, String zip) {
  3. try (ZipFile zipFile = new ZipFile(zip)) {
  4. zipFile.stream()
  5. .forEach(stream::println);
  6. } catch (IOException e) {
  7. // error while opening a ZIP file
  8. }
  9. }
  10. }
复制代码

如下文所示,有了Stream API,我们有了更多更有趣的方式来处理ZIP文件。

对ZIP压缩包的内容进行过滤和排序
  1. public void printEntries(PrintStream stream, String zip) {
  2. try (ZipFile zipFile = new ZipFile(zip)) {
  3. Predicate<ZipEntry> isFile = ze -> !ze.isDirectory();
  4. Predicate<ZipEntry> isJava = ze -> ze.getName().matches(".*java");
  5. Comparator<ZipEntry> bySize =
  6. (ze1, ze2) -> Long.valueOf(ze2.getSize() - ze1.getSize()).intValue();
  7. zipFile.stream()
  8. .filter(isFile.and(isJava))
  9. .sorted(bySize)
  10. .forEach(ze -> print(stream, ze));
  11. } catch (IOException e) {
  12. // error while opening a ZIP file
  13. }
  14. }
  15. private void print(PrintStream stream, ZipEntry zipEntry) {
  16. stream.println(zipEntry.getName() + ", size = " + zipEntry.getSize());
  17. }
复制代码

在迭代ZIP压缩包的条目时,我检查了这个条目是否是一个文件并且是否匹配一个给定的字段(为了简单,直接把匹配字段硬编码在代码中了),然后利用一个给定的比较器,对这些条目按照大小进行了排序。

为ZIP压缩包创建文件索引

在这个例子中,我把ZIP压缩包中的条目按照文件名的首字母分组,建立形如Map>的索引,预想的结果应该看起来像这样简单:

  1. a = [someFile/starting/with/an/A]
  2. u = [someFile/starting/with/an/U, someOtherFile/starting/with/an/U]
复制代码

同样,使用Stream API来实现这个功能非常简单:

  1. public void printEntries(PrintStream stream, String zip) {
  2. try (ZipFile zipFile = new ZipFile(zip)) {
  3. Predicate<ZipEntry> isFile = ze -> !ze.isDirectory();
  4. Predicate<ZipEntry> isJava = ze -> ze.getName().matches(".*java");
  5. Comparator<ZipEntry> bySize =
  6. (ze1, ze2) -> Long.valueOf(ze2.getSize()).compareTo(Long.valueOf(ze1.getSize()));
  7. Map<String, List<ZipEntry>> result = zipFile.stream()
  8. .filter(isFile.and(isJava))
  9. .sorted(bySize)
  10. .collect(groupingBy(this::fileIndex));
  11. result.entrySet().stream().forEach(stream::println);
  12. } catch (IOException e) {
  13. // error while opening a ZIP file
  14. }
  15. }
  16. private String fileIndex(ZipEntry zipEntry) {
  17. Path path = Paths.get(zipEntry.getName());
  18. Path fileName = path.getFileName();
  19. return fileName.toString().substring(0, 1).toLowerCase();
  20. }
复制代码
在ZIP压缩包的文件中查找字段

在这最后一个例子中,我在压缩包中的查找所有以.java结尾的且包含@Test字段的文件,这次,我将利用BufferedReader类的lines方法来实现,这个lines方法按行返回文件流。

  1. public void printEntries(PrintStream stream, String zip) {
  2. try (ZipFile zipFile = new ZipFile(zip)) {
  3. Predicate<ZipEntry> isFile = ze -> !ze.isDirectory();
  4. Predicate<ZipEntry> isJava = ze -> ze.getName().matches(".*java");
  5. List<ZipEntry> result = zipFile.stream()
  6. .filter(isFile.and(isJava))
  7. .filter(ze -> containsText(zipFile, ze, "@Test"))
  8. .collect(Collectors.toList());
  9. result.forEach(stream::println);
  10. } catch (IOException e) {
  11. // error while opening a ZIP file
  12. }
  13. }
  14. private boolean containsText(ZipFile zipFile, ZipEntry zipEntry, String needle) {
  15. try (InputStream inputStream = zipFile.getInputStream(zipEntry);
  16. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
  17. Optional<String> found = reader.lines()
  18. .filter(l -> l.contains(needle))
  19. .findFirst();
  20. return found.isPresent();
  21. } catch (IOException e) {
  22. return false;
  23. }
  24. }
复制代码
总结

在我看来,Stream API提供了一个强大的并且相对更容易的方案来解决遍历ZIP压缩包中的条目的问题。
本文中出现的例子只是用来演示说明Stream API的用法的,都是相对容易的,但我希望你能够喜欢这些例子,并且觉得他对你有用。

引用

http://docs.oracle.com/javase/tutorial/index.html

原文链接: javacodegeeks 翻译: ImportNew.com - xiafei
译文链接: http://www.importnew.com/12800.html

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 13:32

Copyright 2015-2025 djqfx

返回顶部