9

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.

3 Answers 3

17

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't it be better to use with-open for the FileInputStream?
4

These days you can also do:

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

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.