20

clj-httpを使用してダウンロードしたファイルを保存しようとしています

次のコードがあります。

(def test-file
  (cl/get "http://placehold.it/350x150"))

(defn write-file []
   (with-open [w (clojure.java.io/writer  "test-file.gif" :append true)]
(.write w (:body test-file))))

バイト配列として作成しようとすると、例外が発生します。

       user=>     (def test-file
                    (cl/get "http://placehold.it/350x150" {:as :byte-array}))
       #'user/test-file
       user=> (write-file)
       IllegalArgumentException No matching method found: write for class java.io.BufferedWriter  clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:79)

ヘルプ!

4

1 に答える 1

34

バイナリ出力を使用します。

(def test-file
  (client/get "http://placehold.it/350x150" {:as :byte-array}))

(defn write-file []
   (with-open [w (java.io.BufferedOutputStream. (java.io.FileOutputStream. "test-file.gif"))]
     (.write w (:body test-file))))

編集: 出力ストリームの方が優れています:

(defn write-file []
   (with-open [w (clojure.java.io/output-stream "test-file.gif")]
     (.write w (:body test-file))))

アップデート:

エレガントな方法:

(clojure.java.io/copy
 (:body (client/get "http://placehold.it/350x150" {:as :stream}))
 (java.io.File. "test-file.gif"))
于 2012-07-04T02:39:27.260 に答える