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

前端 未结 6 1488
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:33

    A quick make-shift solution may be this code:

    (defn slurpb [is]
      "Convert an input stream is to byte array"
      (with-open [baos (java.io.ByteArrayOutputStream.)]
        (let [ba (byte-array 2000)]
          (loop [n (.read is ba 0 2000)]
            (when (> n 0)
              (.write baos ba 0 n)
              (recur (.read is ba 0 2000))))
          (.toByteArray baos))))
    
    ;;test
    (String. (slurpb (java.io.ByteArrayInputStream. (.getBytes "hello"))))
    

提交回复
热议问题