问题描述
我需要将存储在磁盘上的 Nippy 数据结构转换为 Nippy 可以读取的数据吗?Nippy 使用字节数组,因此我需要某种方法将文件转换为字节数组.我试过了
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))
但这给了
java.lang.IllegalArgumentException: Value out of range for byte: ?
然后我尝试:
(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.
首先要编写 Nippy 结构,我使用:
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)))))
推荐答案
我不知道 Clojure 有什么内置的可以处理这个问题.您绝对不想要 slurp
因为这会将流内容解码为文本.
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.
您可以编写自己的方法来执行此操作,基本上是从 InputStream
读取到缓冲区并将缓冲区写入 java.io.ByteArrayOutputStream
.或者你可以使用 IOUtils来自 Apache Commons IO 的
类:
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))
您还应该看看 Nippy 的 thaw-from-in!
和 freeze-to-out!
函数:
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)))
这篇关于如何在 Clojure 中将整个二进制文件(Nippy)读入字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!