【问题标题】:Java Nio Zip fileJava Nio 压缩文件
【发布时间】:2018-03-13 11:28:36
【问题描述】:

这似乎是一件非常愚蠢的事情,但我看不出我做错了什么。 我有一个包含多个 zip 文件的文件夹。每个 zip 文件至少包含一个名为 sometingXYZsomething 的文件。我想在不解压缩每个 zip 的情况下读取每个文件 sometingXYZsomething,所以,让我们说。 我的代码是:

 try (Stream<Path> paths = Files.walk(Paths.get(FOLDER_NAME)))
 {

    paths
      .filter(p -> p.toString().contains("XYZ"))
      .forEach(p -> readFileXYZ(Paths.get(p.getName())));

  }
  catch (IOException e)
  {
    e.printStackTrace();
  }

还有

private static void readFileXYZ(Path pathFile)
{    
  try {

    Files.lines(pathFile).forEach(System.out::println);   

  } catch (IOException ex) 
  {
    ex.printStackTrace();
  }
}

测试文件夹有一个 zip,其中包含一个 txt 文档 testFileXYZ.txt,我得到了这个异常

java.nio.file.NoSuchFileException: testFileXYZ.txt
testFileXYZ.txt
    at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)

如何在不解压的情况下获取 zip 中的 txt 文件流?

【问题讨论】:

  • 没错,这是一个额外的步骤。我更新代码

标签: java nio


【解决方案1】:

您遇到的问题是您实际上并没有解压缩 ZipFile 的内容。 ZipFile.stream() 允许您遍历 Zip 元数据(Zip 中的文件名列表),但实际上并不解压缩内容供您阅读。为此,您需要使用从 ZipFile 获取的 InputStream,然后读取它以获取您的内容。我在下面提供了一个例子。还有其他方法可以做到这一点(例如使用 ZipInputStream),但我想将我的示例基于您提供的代码。希望这会有所帮助!

private static void openZip(String zipPath)
{
    try (ZipFile zipFile = new ZipFile(zipPath))
    {
        zipFile.stream()
                .filter(p -> p.toString().contains("XYZ"))
                .forEach(p -> readFileXYZ(p, zipFile));

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

private static void readFileXYZ(ZipEntry zipEntry, ZipFile zipFile)
{
    try {
        InputStream inputStream = zipFile.getInputStream(zipEntry);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        bufferedReader.close();
    } 
    catch (IOException ex)
    {
        ex.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多