【问题标题】:Clojure spit behaviour on byte arraysClojure 在字节数组上吐出行为
【发布时间】:2016-06-04 01:17:48
【问题描述】:

以下代码:

(spit "/Users/nha/tmp/spit.txt" (.getBytes "hello"))

生成一个包含“[B@71e054bc”的文件,该文件与内容无关(在本例中为“hello”),因为这是JVM representation of the address of a byte array

但是以下工作(取自this SO post):

  (clojure.java.io/copy
   (.getBytes "hello")
   (java.io.File. "/Users/nha/tmp/spit.txt"))

然后该文件包含正确的内容“hello”。

为什么spit 会这样?有没有办法扩展它的字节行为?

【问题讨论】:

  • 您可以将字节包装在一个字符串中,(spit "spit.txt" (String. (.getBytes "hello")))?很难看出这有什么用,特别是因为原始字节没有编码并且输出将取决于平台。

标签: file clojure


【解决方案1】:

这个问题并不是字节数组特有的。

(spit "spit.txt" (Object.))
(slurp "spit.txt")              ;; => "java.lang.Object@90b293d"

查看source of spit,您会发现它只是在写出参数之前尝试获取参数的字符串表示形式。

您可以尝试在写入之前将任何字节数组包装在一个新字符串中,但请注意选择正确的编码。

;; platform-dependent!
(spit "spit.txt" (String. b))

;; better
(spit "spit.txt" (String. b java.nio.charset.StandardCharsets/UTF_8))

【讨论】:

    【解决方案2】:

    原因是内容传递给str

    你可以通过(source spit)查看:

    user=> (source spit)
    (defn spit
      "Opposite of slurp.  Opens f with writer, writes content, then
      closes f. Options passed to clojure.java.io/writer."
      {:added "1.2"}
      [f content & options]
      (with-open [^java.io.Writer w (apply jio/writer f options)]
        (.write w (str content))))
    ;            - ^^^ - here
    

    因此你得到了字节数组的字符串表示

    编辑:由于spitslurp 的“逆”,它为您提供了一个字符串,这是有道理的并且是一致的行为

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      相关资源
      最近更新 更多