关于jar:clojure:解压缩作为资源存储的zip文件

clojure: unzipping a zip file stored as a resource

我一直在努力读取我的lein项目中资源目录的内容。我现在理解(一段时间做错了之后)使用clojure.java.io/resource提取资源,因为当将文件系统打包为jar时,仅使用文件系统不起作用:

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

这将返回一个BufferedInputStream。我想要做的是获取此zip文件并将其解压缩到本地目录。我不能用它做一个ZipFile,但是我可以做一个ZipInputStream。不幸的是,尽管我可以从中获得ZipEntries,但我需要一个ZipFile才能实际读取ZipEntry的内容。我可以这样做:

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

这将返回名称,但是api文档中没有任何内容可以使用ZipInputStream来获取该ZipEntry的实际内容!

如何将ZipInputStream中的内容写到本地目录? (将代码打包到jar中时也可以使用!)


获得下一个条目后,您可以简单地从ZipInputStream中读取。使用条目中的大小信息来读取内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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!\
\
\
\
"