title: How to zip folders & subfolders with files in it in Kotlin using ZipOutputStream?
body: <p>I have list of files arranges in different directories, some directories will have sub-directories and files in it. I am not able to successfully put same directory structure within a zip file. Here is my code: </p>
  
  <pre><code>fun zipAll(directory: String, zipFile: String) {
  val sourceFile = File(directory)
  
   ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use {
         zipFiles(it, sourceFile)
     }
  }
  
  private fun zipFiles(zipOut: ZipOutputStream, directory: File) {
  
  val data = ByteArray(1024)
  
  zipOut.use {
  
      if (directory.isDirectory) {
          //Adding directory
          it.putNextEntry(ZipEntry(directory.name))
      } else {
          zipFiles(zipOut, directory)
      }
  
      for (f in directory.listFiles()) {
  
          if (!f.name.contains(".zip") &amp;&amp; f.exists()) {
  
              //Adding file
  
              FileInputStream(f).use { fi -&gt;
                  BufferedInputStream(fi).use { origin -&gt;
                      val entry = ZipEntry(f.name)
                      it.putNextEntry(entry)
                      while (true) {
                          val readBytes = origin.read(data)
                          if (readBytes == -1) {
                              break
                          }
                          it.write(data, 0, readBytes)
                      }
                  }
              }
          }
      }
  }
  }
  </code></pre>