簡體   English   中英

如何使用 Clojure 遞歸壓縮文件夾

[英]How to zip a folder recursively with Clojure

我想用 clojure 遞歸壓縮一個文件夾。 這種文件夾的一個例子是

├── a
├── b
│   ├── c
│   │   └── ccc.txt
│   └── bb.txt
├── c
├── a.txt
└── b.txt

選項 1:在 Clojure 中使用操作系統

在 Ubuntu 中使用zip是在此結構的根目錄中執行以下操作:

zip -r result.zip *

但是你必須在工作目錄中才能做到這一點。 使用絕對路徑會產生其他結果,而忽略所有路徑當然會使結構變平。

問題是您無法更改 Clojure 中的工作目錄,我不知道這是..

選項 2:使用原生 Clojure(或 Java)

這應該是可能的,我在 Clojure 或 Java 包裝器中找到了一些 zip 實現。 然而,其中大多數用於單個文件。

這可能是一個解決方案: http : //www.java-forums.org/blogs/java-io/973-how-work-zip-files-java.html

但在我嘗試之前,我想現在或者周圍沒有一個好的 Clojure 庫。

像這樣使用clojure.core/file-seq怎么樣

(require '[clojure.java.io :as io])
(import '[java.util.zip ZipEntry ZipOutputStream])

(with-open [zip (ZipOutputStream. (io/output-stream "foo.zip"))]
  (doseq [f (file-seq (io/file "/path/to/directory")) :when (.isFile f)]
    (.putNextEntry zip (ZipEntry. (.getPath f)))
    (io/copy f zip)
    (.closeEntry zip)))

您可以使用包裝Apache Ant 的rtcritical/clj-ant-tasks庫,並在一行代碼中進行壓縮/解壓縮。

添加庫依賴 [rtcritical/clj-ant-tasks "1.0.1"]

(require '[rtcritical.clj-ant-tasks :refer [run-ant-task])

要壓縮目錄:

(run-ant-task :zip {:destfile "/tmp/archive.zip" :basedir "/tmp/archive"})

壓縮一個目錄,其中基本目錄包含在存檔中:

(run-ant-task :zip {:destfile "/tmp/archive.zip" 
                    :basedir "/tmp" 
                    :includes "archive/**"})

注意:此庫命名空間中的 run-ant-task(s) 函數也可用於運行任何其他 Apache Ant 任務。

有關更多信息,請參閱https://github.com/rtcritical/clj-ant-tasks

檢查https://github.com/AeroNotix/swindon一個很好的圍繞 java.util.zip 的小包裝。 使用流https://github.com/chmllr/zeus一個簡單的 Clojure 庫進行基於 zip 的壓縮

基於@Kyle 的回答:

(require '[clojure.java.io :as io])
(import '[java.util.zip ZipEntry ZipOutputStream])


(defn zip-folder
  "p input path, z output zip"
  [p z]
  (with-open [zip (ZipOutputStream. (io/output-stream z))]
    (doseq [f (file-seq (io/file p)) :when (.isFile f)]
      (.putNextEntry zip (ZipEntry. (str/replace-first (.getPath f) p "") ))
      (io/copy f zip)
      (.closeEntry zip)))
  (io/file z))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM