Clojure: unpacking a zip file saved as a resource

I tried my best to read the contents of the resource directory in my lein project. Now I understand (after incorrect use) to use clojure.java.io/resource to pull out a resource, because just using the file system does not work when it is packaged like a jar:

> (require '[clojure.java.io :as io]) > (def zipzip (.openStream (io/resource "zip.zip"))) 

This returns a BufferedInputStream . I want to make this zip file and unzip it to a local directory. I cannot make a ZipFile from it, but I can make a ZipInputStream . Unfortunately, although I can get ZipEntries from this, I need a ZipFile to really read the contents of ZipEntry . I can do it:

 > (-> zipzip ZipInputStream. .getNextEntry .getName) 

This returns the name, but there is nothing in the api docs to get the actual contents of this ZipEntry using ZipInputStream !

How to write contents from this ZipInputStream to a local directory? (this also works when the code is packaged in a jar!)

+6
source share
1 answer

You can just read from ZipInputStream after you got the next record. Use the size information from the record to read the content.

 user=> (import 'java.util.zip.ZipInputStream) java.util.zip.ZipInputStream user=> (def zs (ZipInputStream. (io/input-stream "foo.zip"))) #'user/zs user=> (def ze (.getNextEntry zs)) #'user/ze user=> (.getName ze) "foo.txt" user=> (.getSize ze) 21 user=> (let [bytes (byte-array 21)] (.read zs bytes 0 21) (String. bytes "UTF-8")) "Das ist ein Test!\r\n\r\n" 
+8
source

Source: https://habr.com/ru/post/913400/


All Articles