clojure - 如何在 Clojure 中将序列转换为 byte[]?

标签 clojure clojure-contrib

我需要将原始字节写入文件。我这样做是:

(.write (FileOutputStream "/path") bytes)

...其中字节必须是 byte[] 类型。请注意它不能是Byte[]。

我尝试使用(字节)和/或(数组)函数转换我的序列,但很沮丧,例如:

user=> (bytes (into-array (filter #(not (= % 13)) (to-byte-array (File. "e:/vpn.bat")))))
java.lang.ClassCastException: [Ljava.lang.Byte; cannot be cast to [B (NO_SOURCE_FILE:0)

继续:

带有 Byte/TYPE 的数组工作正常。然而,字节数组却没有。文件变空:

(import 'FileOutputStream)
(use 'clojure.contrib.io)

(defn remove-cr-from-file [file]
  (with-open [out (FileOutputStream. file)]
    (let [dirty-bytes (to-byte-array file)
          clean-seq   (filter #(not (= 13 %)) dirty-bytes)
          clean-bytes (byte-array clean-seq)]
      (.write out clean-bytes))))

最佳答案

还有字节数组函数。

如果需要打包字节数组,您可以查看 http://github.com/geoffsalmon/bytebuffer或者直接使用底层的 Java ByteBuffer 东西。

关于clojure - 如何在 Clojure 中将序列转换为 byte[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3450954/

相关文章:

recursion - 如何避免clojure递归函数中的stackoverflow?

java - 将 LazySeq 从 Clojure 返回到 Java 时出现 ClassCastException

unit-testing - (clojure 测试) 配置 leiningen 以在 src 中运行测试(不仅在测试目录中)

java - 如何从 Java 调用 Clojure 宏?

clojure - defadt 在新的 clojure contrib 中去了哪里?

clojure - 如何动态定义规范?

recursion - 使用 recur 时传递给关键字的参数数量错误

json - 如何扩展 clojure.contribs json writer 以序列化其他类

clojure - 如何找到我的哪些依赖项正在下载特定的 jar?