如何检查生成的zip文件是否已损坏? [英] How to check if a generated zip file is corrupted?
问题描述
我们有一段代码可以在我们的系统上生成一个zip文件。一切都还可以,但有时这个由FilZip或WinZip打开的zip文件被认为已损坏。
we have a piece of code which generates a zip file on our system. Everything is ok, but sometimes this zip file while opened by FilZip or WinZip is considered to be corrupted.
所以这是我的问题:我们如何以编程方式检查生成zip文件已损坏?
So here is my question: how can we check programatically if a generated zip file is corrupted?
以下是我们用于生成zip文件的代码:
Here is the code we are using to generate our zip files:
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tmpFile));
byte[] buffer = new byte[16384];
int contador = -1;
for (DigitalFile digitalFile : document.getDigitalFiles().getContent()) {
ZipEntry entry = new ZipEntry(digitalFile.getName());
FileInputStream fis = new FileInputStream(digitalFile.getFile());
try {
zos.putNextEntry(entry);
while ((counter = fis.read(buffer)) != -1) {
zos.write(buffer, 0, counter);
}
fis.close();
zos.closeEntry();
} catch (IOException ex) {
throw new OurException("It was not possible to read this file " + arquivo.getId());
}
}
try {
zos.close();
} catch (IOException ex) {
throw new OurException("We couldn't close this stream", ex);
}
我们在这里有什么问题吗?
Is there anything we are doing wrong here?
编辑:
实际上,上面的代码绝对没问题。我的问题是我正在为我的用户重定向错误的流。因此,不是打开一个zip文件,而是打开一些完全不同的东西。 Mea culpa :(
Actually, the code above is absolutely ok. My problem was that I was redirecting the WRONG stream for my users. So, instead of opening a zip file they where opening something completely different. Mea culpa :(
但主要问题仍然存在:如何以编程方式验证给定的zip文件是否未损坏?
BUT the main question remains: how programatically I can verify if a given zip file is not corrupted?
推荐答案
您可以使用 ZipFile
类来检查您的文件:
You can use the ZipFile
class to check your file :
static boolean isValid(final File file) {
ZipFile zipfile = null;
try {
zipfile = new ZipFile(file);
return true;
} catch (IOException e) {
return false;
} finally {
try {
if (zipfile != null) {
zipfile.close();
zipfile = null;
}
} catch (IOException e) {
}
}
}
这篇关于如何检查生成的zip文件是否已损坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!