【问题标题】:Can't get zip entries from DataInputStream无法从 DataInputStream 获取 zip 条目
【发布时间】:2014-07-16 09:44:48
【问题描述】:

我必须解压缩一个通过 URL 寻址的 zip 数据包。 (URL和DataInputStream都是正确的!)

private void unZipIt(File baseDir, DataInputStream dis, PipedOutputStream pos) throws ZipException
{
    byte[] buffer = new byte[1024];
    String fileName = "";
    File newFile;
    FileOutputStream fos = null;

    try
    {
        ZipInputStream zis = new ZipInputStream(dis);
        ZipEntry ze = zis.getNextEntry();

        if(ze==null)
        {
            System.out.println("first zip entry is null");
        }

        while (ze != null)
        {
            System.out.println("zip entry is not null");
            fileName = ze.getName();
            newFile = new File(baseDir + File.separator + fileName);

            if (isSavFile(fileName))
            {
                System.out.println(fileName + "is savfile");
                new File(newFile.getParent()).mkdirs();

                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();
        // return true;
    }
    catch (IOException e)
    {
        // ex.printStackTrace();
        log.error("unzipping '" + fileName + "'", e);
        throw new ZipException(fileName, e);
        // return false;
    }

但无法获取任何 zip 条目。 (第一个 zip 条目为空!) 使用 FileOutputStream 可以完美运行。由于效率原因,我不允许将文件存储在 PC 上。

谁有想法?

【问题讨论】:

  • 更新。我错过了复制最后一个 { 以关闭该方法 - 但它肯定存在 ;)
  • 你能显示调用的代码块“unZipIt”以及如何初始化DataInputStream吗?
  • 当您调用此方法时,您可能已经位于流的末尾。
  • 而且你需要关闭 FileOutputStream,否则你会泄漏文件描述符。
  • DataInputStream 是 url.openStream() - URL 是正确的!调用 UnzipIt(...) 的函数是: private boolean unzipAllFiles() throws ZipException { File savDir = vManager.getSaveDir(); System.out.println("saveDir:" + savDir.getPath()); if (!savDir.exists()) { savDir.mkdir(); } 尝试 { unZipIt(savDir, dis, pos); } catch (ZipException e) { throw e; } 返回真; }

标签: java zip fileinputstream datainputstream


【解决方案1】:

很可能问题在于如何获取作为dis 传递给unZipIt() 方法的输入流。

您不应该收到DataInputStream,而是一个简单的InputStreamZipInputStream 不使用也不期望输入是 DataInputStream

此外,在保存条目的内容时,您应该只读取(并保存)与条目长度一样多的字节,直到有更多字节为止。

【讨论】:

  • 它也不适用于 InputStream 作为参数。谢谢你的提示。如果它开始工作,我会试试看:D
  • 您必须向我们展示您如何创建/获取传递给您的unZipIt() 方法的dis 输入流,很可能错误不在发布的代码中。
  • URL url = 新 URL(fileDownloadDir); URLConnection con = url.openConnection(); DataInputStream dis = new DataInputStream(url.openStream());
  • 好的,所以您需要做的就是将url.openStream() 作为dis 传递给您的unZipIt() 方法,并且一切都应该工作-假设url 指向一个有效的zip 文件。跨度>
  • 现在我将 url.openStream() 传递给 unZipIt() 但第一个条目仍然为空:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
相关资源
最近更新 更多