繁体   English   中英

java提取zip ZLIB输入流的意外结束

[英]java extract zip Unexpected end of ZLIB input stream

我正在创建一个程序,它将提取一个 zip 然后将文件插入到数据库中,我经常收到错误

java.lang.Exception: java.io.EOFException: Unexpected end of ZLIB input stream

我无法确定原因,因为提取代码与您在网络上可以找到的所有其他代码几乎相同。 我的代码如下:

public void extract(String zipName, InputStream content) throws Exception {

    int BUFFER = 2048;

    //create the zipinputstream 
    ZipInputStream zis = new ZipInputStream(content);

    //Get the name of the zip
    String containerName = zipName;

    //container for the zip entry
    ZipEntry entry;

    // Process each entry
    while ((entry = zis.getNextEntry()) != null) {

        //get the entry file name
        String currentEntry = entry.getName();

        try {

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                // establish buffer for writing file
                byte data[] = new byte[BUFFER];
                int currentByte;

                // read and write until last byte is encountered
                while ((currentByte = zis.read(data, 0, BUFFER)) != -1) {

                    baos.write(data, 0, currentByte);
                }

                baos.flush(); //flush the buffer 

                //this method inserts the file into the database
                insertZipEntry(baos.toByteArray());

                baos.close();

        } 
        catch (Exception e) {
            System.out.println("ERROR WITHIN ZIP " + containerName);
        }
    }
}

这可能是由于这个JVM错误引起的(JVM-6519463)

我以前在1000个随机创建的文档中有大约一两个错误,我应用了建议的解决方案(捕获EOFException并且不执行任何操作),我没有更多错误。

我会说你偶尔会被截断Zip文件来处理。 检查上游。

我有同样的例外,问题出在压缩方法上(不是提取)。 写入输出流后,我没有使用zos.closeEntity()关闭 ZipOutputStream。 没有它,压缩效果很好,但提取时出现异常。

public static byte[] zip(String outputFilename, byte[] output) {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ZipOutputStream zos = new ZipOutputStream(baos)) {
        zos.putNextEntry(new ZipEntry(outputFilename));
        zos.write(output, 0, output.length);            
        zos.closeEntry(); //this line must be here
        return baos.toByteArray();
    } catch (IOException e) {
        //catch exception
    }
}

永远不要尝试读取比条目包含的更多的字节。 调用ZipEntry.getSize()以获取条目的实际大小,然后使用此值来跟踪条目中读取时剩余的字节数。 见下文 :

try{    

   ...

   int bytesLeft = (int)entry.getSize();
   while ( bytesLeft>0 && (currentByte=zis.read(data, 0, Math.min(BUFFER, bytesLeft))) != -1) {
     ...
  }

  ...

  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM