How to read a whole binary file (Nippy) into byte array in Clojure?

前端 未结 6 1493
Happy的楠姐
Happy的楠姐 2021-01-12 18:05

I need to convert Nippy data structures stored on disk into something that can be read by Nippy? Nippy uses byte arrays, so I need some way to convert the file into a byte a

6条回答
  •  佛祖请我去吃肉
    2021-01-12 18:46

    Since you know the .length of the file, you can allocate once and use DataInputStream's readFully method. No additional libraries, buffer copies, or loops required.

    (defn file-to-byte-array
      [^java.io.File file]
      (let [result (byte-array (.length file))]
        (with-open [in (java.io.DataInputStream. (clojure.java.io/input-stream file))]
          (.readFully in result))
        result))
    

提交回复
热议问题