Search code examples
javazip

Util creates "corrupt" zip files


I'm zipping up the contents of a directory, but running into an error when trying to open the zipped up files. Can anyone tell what's going on with my code? Perhaps I'm not allocating enough bytes?

Look inside zipDirectory() and you will see that I'm zipping up folders which contain special extension files. Not sure where the error's occurring, so maybe someone can help me out there!

private void zipDirectory() {
   File lazyDirectory = new File(defaultSaveLocation);
   File[] files = lazyDirectory.listFiles();

   for (File file : files) {
      if (file.isDirectory()) {
         System.out.println("Zipping up " + file);
         zipContents(file);
      }
   }
}

public static void addToZip(String fileName, ZipOutputStream zos) throws IOException {
    System.out.println("Writing '" + fileName + "' to zip file");

    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zos.putNextEntry(zipEntry);

    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
    }

    zos.closeEntry();
    fis.close();
}

public static void zipContents(File dirToZip) {
    List<File> fileList = new ArrayList<File>();
    File[] filesToZip = dirToZip.listFiles();
    for (File zipThis : filesToZip) {
        String ext = "";
        int i = zipThis.toString().lastIndexOf('.');
        if (i > 0) {
            ext = zipThis.toString().substring(i+1);
        }
        if(ext.matches("cpp|bem|gz|h|hpp|pl|pln|ppcout|vec|xml|csv")){
            fileList.add(zipThis);
        }
    }
    
    try {
        FileOutputStream fos = new FileOutputStream(dirToZip.getName() + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        for (File file : fileList) {
            addToZip(file.toString(), zos);
        }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

enter image description here


Solution

  • Like most issues with IO streams in Java, your fault is almost certainly that you are not closing the streams properly. You need to add:

    zos.finish(); // good practice
    zos.close();
    

    after the for loop.