如何下载文件并以Clojure从内存解压缩? [英] How to download a file and unzip it from memory in clojure?
问题描述
我正在使用clj-http发出GET请求,响应是一个zip文件.此zip的内容始终是一个CSV文件.我想将CSV文件保存到磁盘,但是我不知道如何保存.
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 figure out how.
如果我将文件放在磁盘上,那么Raynes/fs库中的(fs/unzip文件名目标位置)
效果很好,但我不知道如何强制clj-http变成可以读取的内容.如果可能的话,我想直接将文件解压缩,而无需
If I have the file on disk, (fs/unzip filename destination)
from the Raynes/fs library works great, but I can't figure out how I can coerce the response from clj-http into something this can read. If possible, I'd like to unzip the file directly without
距离我最近的地方(如果距离很近的话)将我带到BufferedInputStream,但是我从那里迷路了.
The closest I've gotten (if this is even close) gets me to a BufferedInputStream, but I'm lost from there.
(require '[clj-http.client :as client])
(require '[clojure.java.io :as io])
(->
(client/get "http://localhost:8000/blah.zip" {:as :byte-array})
(:body)
(io/input-stream))
推荐答案
您可以使用纯 java.util.zip.GZIPInputStream .取决于内容的压缩方式.这是使用java.util.zip.GZIPInputStream保存文件的代码:
You can use the pure java java.util.zip.ZipInputStream or java.util.zip.GZIPInputStream. Depends how the content is zipped. This is the code that saves your file using java.util.zip.GZIPInputStream :
(->
(client/get "http://localhost:8000/blah.zip" {:as :byte-array})
(:body)
(io/input-stream)
(java.util.zip.GZIPInputStream.)
(clojure.java.io/copy (clojure.java.io/file "/path/to/output/file")))
使用java.util.zip.ZipInputStream使其更加复杂:
Using java.util.zip.ZipInputStream makes it only a bit more complicated :
(let [stream (->
(client/get "http://localhost:8000/blah.zip" {:as :byte-array})
(:body)
(io/input-stream)
(java.util.zip.ZipInputStream.))]
(.getNextEntry stream)
(clojure.java.io/copy stream (clojure.java.io/file "/path/to/output/file")))
这篇关于如何下载文件并以Clojure从内存解压缩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!