Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure, file to byte array?

Tags:

clojure

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.

like image 647
insudo Avatar asked Nov 06 '14 22:11

insudo


2 Answers

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)
like image 88
ztellman Avatar answered Sep 23 '22 21:09

ztellman


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")
like image 36
a.k Avatar answered Sep 22 '22 21:09

a.k