Search code examples
clojure

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.


Solution

  • 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)