Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

java - How to check if a generated zip file is corrupted?

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.

So here is my question: how can we check programatically if a generated zip file is corrupted?

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?

EDIT: 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 :(

BUT the main question remains: how programatically I can verify if a given zip file is not corrupted?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...