如何在输入流中包装字符串

如何在输入流中包装字符串

本文介绍了如何在输入流中包装字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以一种可以测试以下功能的方式将字符串包装在输入流中?

How can I wrap a string in an input-stream in such a way that I can test the function bellow?

(defn parse-body [body]
    (cheshire/parse-stream  (clojure.java.io/reader body) true))

(deftest test-parse-body
    (testing "read body"
        (let [body "{\"age\": 28}"]  ;; must wrap string
            (is (= (parse-body body) {:age 28}))
            )))


推荐答案

首先使用主机互操作从字符串构造一个InputStream,方法是先转换为字节数组:

It is straightforward to construct an InputStream from a String using host interop, by converting to a byte-array first:

(defn string->stream
  ([s] (string->stream s "UTF-8"))
  ([s encoding]
   (-> s
       (.getBytes encoding)
       (java.io.ByteArrayInputStream.))))

作为另一个流和字节互操作示例,这是一个函数,该函数返回将String编码为给定格式时产生的字节向量:

As another stream and byte interop example, here's a function that returns a vector of the bytes produced when encoding a String to a given format:

(defn show-bytes
  [s encoding]
  (let [buf (java.io.ByteArrayOutputStream.)
        stream (string->stream s encoding)
        ;; worst case, 8 bytes per char?
        data (byte-array (* (count s) 8))
        size (.read stream data 0 (count data))]
    (.write buf data 0 size)
    (.flush buf)
    (apply vector-of :byte (.toByteArray buf))))

+user=> (string->stream "hello")
#object[java.io.ByteArrayInputStream 0x39b43d60 "java.io.ByteArrayInputStream@39b43d60"]
+user=> (isa? (class *1) java.io.InputStream)
true
+user=> (show-bytes "hello" "UTF-8")
[104 101 108 108 111]
+user=> (show-bytes "hello" "UTF-32")
[0 0 0 104 0 0 0 101 0 0 0 108 0 0 0 108 0 0 0 111]

这篇关于如何在输入流中包装字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:46