Skip to content

Instantly share code, notes, and snippets.

@scotthaleen
Created October 20, 2016 21:15
Show Gist options
  • Save scotthaleen/936124d78d591c3bb188b97be6e39528 to your computer and use it in GitHub Desktop.
Save scotthaleen/936124d78d591c3bb188b97be6e39528 to your computer and use it in GitHub Desktop.
Clojure: read an io/stream to a byte array
(require '[clojure.java.io :as io])
(def fp "/path/to/file")
(defn stream->bytes [is]
(loop [b (.read is) accum []]
(if (< b 0)
accum
(recur (.read is) (conj accum b)))))
(with-open [is (io/input-stream (io/as-file fp))]
(stream->bytes is))
@aaronblenkush
Copy link

That actually returns a PersistentVector, not a byte array. And it would be really inefficient.

Better to use a library like byte-streams, or just use Java interop:

(defn stream-bytes [is]
  (let [baos (java.io.ByteArrayOutputStream.)]
    (io/copy is baos)
    (.toByteArray baos))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment