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 array. I have tried
(clojure.java.io/to-byte-array (clojure.java.io/file folder-path file-path))
but this gives
java.lang.IllegalArgumentException: Value out of range for byte: ?
Then I try:
(into-array Byte/TYPE (map byte (slurp (clojure.java.io/file folder-path file-path))))
but somehow the namespace is wrong, and I can't find the right one.
To write the Nippy structures in the first place, I am using:
(with-open [w (clojure.java.io/output-stream file-path)]
(.write w (nippy/freeze data)))))
You can give a try to ClojureWerk's Buffy : https://github.com/clojurewerkz/buffy.
Buffy is a Clojure library for working with binary data, writing complete binary protocol implementations in Clojure, storing complex data structures in an off-heap cache, reading binary files and doing everything you would usually do with ByteBuffer.
It's very neat if your binary data is structured as you can define complex composite types and frames depending on structure types, even decode UTF.
Since you know the
.length
of the file, you can allocate once and useDataInputStream
'sreadFully
method. No additional libraries, buffer copies, or loops required.Here's how I do it generically with clojure built-ins
Please note that I just cut Nippy v2.13.0 which now includes a pair of helper utils to help simplify this use case:
freeze-to-file
andthaw-from-file
.Release details at: https://github.com/ptaoussanis/nippy/releases/tag/v2.13.0
Cheers!
A quick make-shift solution may be this code:
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 ajava.io.ByteArrayOutputStream
. Or you could use theIOUtils
class from Apache Commons IO:You should also take a look at Nippy's
thaw-from-in!
andfreeze-to-out!
functions: