How to download a file and unzip it from memory in clojure?

前端 未结 2 2072
名媛妹妹
名媛妹妹 2021-02-14 01:12

I\'m making a GET request using clj-http and the response is a zip file. The contents of this zip is always one CSV file. I want to save the CSV file to disk, but I can\'t figur

2条回答
  •  花落未央
    2021-02-14 01:46

    (require '[clj-http.client :as httpc])
    (import '[java.io File])
    
    
    (defn download-unzip [url dir]
      (let [saveDir (File. dir)]
        (with-open [stream (-> (httpc/get url {:as :stream})
                               (:body)
                               (java.util.zip.ZipInputStream.))]
          (loop [entry (.getNextEntry stream)]
            (if entry
              (let [savePath (str dir File/separatorChar (.getName entry))
                    saveFile (File. savePath)]
                (if (.isDirectory entry)
                  (if-not (.exists saveFile)
                    (.mkdirs saveFile))
                  (let [parentDir (File. (.substring savePath 0 (.lastIndexOf savePath (int File/separatorChar))))]
                    (if-not (.exists parentDir) (.mkdirs parentDir))
                    (clojure.java.io/copy stream saveFile)))
                (recur (.getNextEntry stream))))))))
    

提交回复
热议问题