title: Java util zip creates "corrupt" zip files
body: <p>I'm zipping up the contents of a directory, but running into an error when trying to open the zipped up files. </p>
  
  <p>Can anyone tell what's going on with my code? Perhaps I'm not allocating enough bytes?</p>
  
  <p>Look inside zipDirectory() and you will see that I'm zipping up folders which contain special extension files. </p>
  
  <p>Not sure where the error's occurring, so maybe someone can help me out there!</p>
  
  <p>Much appreciated</p>
  
  <pre><code>    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 FileNotFoundException, 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)) &gt;= 0) {
          zos.write(bytes, 0, length);
      }
  
      zos.closeEntry();
      fis.close();
  
      }
  
  public static void zipContents(File dirToZip) {
  
      List&lt;File&gt; fileList = new ArrayList&lt;File&gt;();
  
      File[] filesToZip = dirToZip.listFiles();
  
      for (File zipThis : filesToZip) {
  
          String ext = "";
  
          int i = zipThis.toString().lastIndexOf('.');
  
          if (i &gt; 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 (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        } catch (IOException e) {
           e.printStackTrace();
      }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/VVljJ.jpg" alt="enter image description here"></p>