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.
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With