如何阅读整个二进制文件(刺骨)到字节数组中的Clojure? [英] How to read a whole binary file (Nippy) into byte array in Clojure?

查看:146
本文介绍了如何阅读整个二进制文件(刺骨)到字节数组中的Clojure?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存储在磁盘上到的东西,可以用刺骨的读取刺骨的数据结构转换?刺骨的使用字节数组,所以我需要一些方法来将文件转换为字节数组。我曾尝试

 (clojure.java.io/to-byte-array(clojure.java.io/file文件夹路径的文件路径))

但是这给

  java.lang.IllegalArgumentException异常:值超出了范围字节:?

然后我尝试:

 (成阵字节/ TYPE(图字节(啜食(clojure.java.io/file文件夹路径的文件路径))))

但不知何故,该命名空间是错误的,我无法找到合适的人。

要编写刺骨结构摆在首位,我使用的:

 (用开[W(clojure.java.io/ou​​tput-stream文件路径)]
    (.WRITE W(凛冽/冻结数据)))))


解决方案

我不知道任何东西内置到Clojure中,将处理这个问题。你肯定不希望,因为这将取消code中的流内容文本。

您可以编写自己的方法来做到这一点,从的InputStream 基本上读入缓冲区,将缓冲区​​写入到一个 java.io。 ByteArrayOutputStream 。或者你可以使用 IOUtils 来自Apache下议院IO类

 (需要'[clojure.java.io:作为IO])
 (进口[org.apache.commons.io IOUtils]) (IOUtils / toByteArray(IO /输入流文件路径))

您也应该看看刺骨的解冻 - 从入!冻结到了!功能:

 (进口'[java.io DataInputStream以DataOutputStream类]) (用开[W(IO /输出流文件路径)]
   (刺骨/冻结到了!(DataOutputStream类。w)的一些数据)) (用开[R(IO /输入流文件路径)]
   (刺骨/解冻 - 从入!(DataInputStream所。R)))

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)))))

解决方案

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)))

这篇关于如何阅读整个二进制文件(刺骨)到字节数组中的Clojure?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆