kazuwal
kazuwal

Reputation: 1091

Clojure, file to byte array?

I have a .bson file that I need to add to a byte array before decoding it.

I was wondering if anybody has a solution for how to add a file to a byte array using Clojure?

Thanks.

Upvotes: 9

Views: 6393

Answers (3)

Jeremy Field
Jeremy Field

Reputation: 692

These days you can also do:

(require '[clojure.java.io :as io])

(-> "path/to/thing" io/file .toPath java.nio.file.Files/readAllBytes)

Upvotes: 4

a.k
a.k

Reputation: 1203

somewhat similar to zack's answer, from clojure-docs

(require '[clojure.java.io :as io])

(defn file->bytes [path]
  (with-open [in (io/input-stream path)
              out (java.io.ByteArrayOutputStream.)]
    (io/copy in out)
    (.toByteArray out)))

(file->bytes "/x/y/z.txt")

Upvotes: 2

ztellman
ztellman

Reputation: 776

The most succinct method is just to use the byte-streams library, in which you'd simply call (byte-streams/to-byte-array (java.io.File. "path")).

If you want to do it without an external library, it would be something like:

(let [f (java.io.File. "path")
      ary (byte-array (.length f))
      is (java.io.FileInputStream. f)]
  (.read is ary)
  (.close is)
  ary)

Upvotes: 17

Related Questions