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

前端 未结 6 1485
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:37

    I'm not aware of anything built-in to Clojure that will handle this. You definitely don't want slurp because that will decode the stream contents as text.

    You could write your own method to do this, basically reading from the InputStream into a buffer and writing the buffer to a java.io.ByteArrayOutputStream. Or you could use the IOUtils class from Apache Commons IO:

     (require '[clojure.java.io :as io])
     (import '[org.apache.commons.io IOUtils])
    
     (IOUtils/toByteArray (io/input-stream file-path))
    

    You should also take a look at Nippy's thaw-from-in! and freeze-to-out! functions:

     (import '[java.io DataInputStream DataOutputStream])
    
     (with-open [w (io/output-stream file-path)]
       (nippy/freeze-to-out! (DataOutputStream. w) some-data))
    
     (with-open [r (io/input-stream file-path)]
       (nippy/thaw-from-in! (DataInputStream. r)))
    

提交回复
热议问题