I'm trying to rewrite following snippet in clojure, but it all comes out ugly, maybe someone will suggest a more elegant solution?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipFileRdrExp {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("C:\\MyZip.zip");
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze;
while((ze=zis.getNextEntry())!=null){
System.out.println(ze.getName());
zis.closeEntry();
}
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my ugly try with duplicate call to getNextEntry:
(ns app.core
(:import
(java.io FileInputStream FileNotFoundException IOException File)
(java.util.zip ZipInputStream ZipEntry)))
(defn- read-zip [zip-file]
(let [fis (FileInputStream. zip-file)
zis (ZipInputStream. fis)]
(loop [ze (.getNextEntry zis)]
(when ze
(println (.getName ze))
(.closeEntry zis)
(recur (.getNextEntry zis))))
(.close zis)))
To unzip a zip file, we need to read the zip file with ZipInputStream and then read all the ZipEntry one by one. Then use FileOutputStream to write them to file system. We also need to create the output directory if it doesn't exists and any nested directories present in the zip file.
Java API provides extensive support to read Zip files, all classes related to zip file processing are located in the java. util. zip package. One of the most common tasks related to zip archive is to read a Zip file and display what entries it contains, and then extract them in a folder.
Package java. util. zip Description. Provides classes for reading and writing the standard ZIP and GZIP file formats.
I would go with something like the following:
(defn entries [zipfile]
(lazy-seq
(if-let [entry (.getNextEntry zipfile)]
(cons entry (entries zipfile)))))
(defn walkzip [fileName]
(with-open [z (ZipInputStream. (FileInputStream. fileName))]
(doseq [e (entries z)]
(println (.getName e))
(.closeEntry z))))
EDIT: the above code was eventually tested and corrected.
EDIT: the following works as expected and it's much more concise, even though it uses a different Java API
(defn entries [zipfile]
(enumeration-seq (.entries zipfile)))
(defn walkzip [fileName]
(with-open [z (java.util.zip.ZipFile. fileName)]
(doseq [e (entries z)]
(println (.getName e)))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With