如何用clojure读取ByteBuffer中的字节?

时间:2015-05-05 07:09:53

标签: clojure nio bytebuffer

(let [buffer (ByteBuffer/allocate 8)
      arr (byte-array 2)]
   (doto buffer
      (.putLong 4)
      (.get arr)))

1 个答案:

答案 0 :(得分:3)

问题是什么并不完全清楚,所以这里有一个从java.nio.ByteBuffer读取和写入的例子:

字节:

user> (let [buf-len 8
            buffer (ByteBuffer/allocate buf-len)
            arr (byte-array 2)]
        (doseq [x (range buf-len)]
          (.put buffer x (byte x)))
        (.get buffer arr 0 (count arr))
        (println "buffer contains"
                 (for [x (range buf-len)]
                   (.get buffer x)))
        (println "arr contains" (vec arr)))
buffer contains (0 1 2 3 4 5 6 7)
arr contains [0 1]
nil

和多头:

user> (let [buf-len 8
            buffer (ByteBuffer/allocate buf-len)
            arr (byte-array 2)]
        (.putLong buffer 0 Long/MAX_VALUE)
         (.get buffer arr)
        (println "buffer contains"
                 (for [x (range buf-len)]
                   (.get buffer x)))
        (println "arr contains" (vec arr)))
buffer contains (127 -1 -1 -1 -1 -1 -1 -1)
arr contains [127 -1]
nil

并且您的原始示例非常接近,它只需要偏移量

user> (let [buffer (ByteBuffer/allocate 8)
            arr (byte-array 2)]
        (doto buffer
          (.putLong 0 4)
          (.get arr)))
#<HeapByteBuffer java.nio.HeapByteBuffer[pos=2 lim=8 cap=8]>