我正在创建一个程序,它将提取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);
}
}
}
答案 0 :(得分:2)
我以前在1000个随机创建的文档中有一两个错误,我应用了建议的解决方案(捕获EOFException并且不执行任何操作),我没有更多错误。
答案 1 :(得分:1)
我会说你偶尔会被截断的Zip文件来处理。检查上游。
答案 2 :(得分:-1)
永远不要尝试读取比条目包含的更多字节。调用ZipEntry.getSize()以获取条目的实际大小,然后使用此值来跟踪条目中读取时剩余的字节数。见下文:
try{
...
int bytesLeft = (int)entry.getSize();
while ( bytesLeft>0 && (currentByte=zis.read(data, 0, Math.min(BUFFER, bytesLeft))) != -1) {
...
}
...
}