gpt4 book ai didi

clojure - 将 zip 文件写入 Clojure 中的文件

转载 作者:行者123 更新时间:2023-12-03 00:27:30 27 4
gpt4 key购买 nike

我有一个压缩方法:

    (defn zip-project [project-id notebooks files]
(with-open [out (ByteArrayOutputStream.)
zip (ZipOutputStream. out)]
(doseq [nb notebooks]
(.putNextEntry zip (ZipEntry. (str "Notebooks/" (:notebook/name nb) ".bkr")))
(let [nb-json (:notebook/contents nb)
bytes (.getBytes nb-json)]
(.write zip bytes))
(.closeEntry zip))
(doseq [{:keys [name content]} files]
(.putNextEntry zip (ZipEntry. (str "Files/" name)))
(io/copy content zip)
(.closeEntry zip))
(.finish zip)
(.toByteArray out)))

制作 zip 后,我想将其保存到/tmp/sample/sample.zip 之类的文件中,但我似乎无法制作它。这就是我正在做的事情:

(defn create-file! [path zip]
(let [f (io/file path)]
(io/make-parents f)
(io/copy zip f)
true))

问题是,当我从终端运行 unzip 时,它说 zip 文件是空的,如果我使用 Archive 实用程序解压缩它,它会使用 cpgz 扩展名进行提取。

我在这里做错了什么?

最佳答案

你基本上需要 4 样东西

  1. 导入所有内容(通常您会使用 (ns ...) 但您可以在 repl 中运行它

    (import 'java.io.FileOutputStream)
    (import 'java.io.BufferedOutputStream)
    (import 'java.io.ZipOutputStream)
    (import 'java.util.zip.ZipOutputStream)
    (import 'java.util.zip.ZipEntry)
  2. 您需要一种方法来初始化流。这可以通过 -> 宏很好地完成:

    (defn zip-stream
    "Opens a ZipOutputStream over the given file (as a string)"
    [file]
    (-> (FileOutputStream. file)
    BufferedOutputStream.
    ZipOutputStream.))
  3. 您需要一种在 ZipOutputStream 中创建/关闭条目的方法

    (defn create-zip-entry
    "Create a zip entry with the given name. That will be the name of the file inside the zipped file."
    [stream entry-name]
    (.putNextEntry stream (ZipEntry. entry-name)))
  4. 最后,您需要一种编写内容的方法。

    (defn write-to-zip
    "Writes a string to a zip stream as created by zip-stream"
    [stream str]
    (.write stream (.getBytes str)))
  5. 把它们放在一起:

    (with-open [stream (zip-stream "coolio.zip")]
    (create-zip-entry stream "foo1.txt")
    (write-to-zip stream "Hello Foo1")
    (.closeEntry stream) ;; don't forget to close entries
    (create-zip-entry stream "foo2.txt")
    (write-to-zip stream "Hello Foo 2")
    (.closeEntry stream))
  6. 结果:

The result

关于clojure - 将 zip 文件写入 Clojure 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754591/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com