【问题标题】:How do I create an input stream that reads from a string instead of a file or url如何创建从字符串而不是文件或 url 读取的输入流
【发布时间】:2011-06-18 19:22:49
【问题描述】:

我想将*in* 绑定到从字符串而不是“真实”输入流中读取的流。我该怎么做?

【问题讨论】:

    标签: clojure inputstream


    【解决方案1】:

    查看with-in-str:

    http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/with-in-str

    ClojureDocs 有一个使用示例:

    ;; Given you have a function that will read from *in*
    (defn prompt [question]
      (println question)
      (read-line))
    
    user=> (prompt "How old are you?")
    How old are you?
    34                   ; <== This is what you enter
    "34"                 ; <== This is returned by the function
    
    ;; You can now simulate entering your age at the prompt by using with-in-str
    
    user=> (with-in-str "34" (prompt "How old are you?"))
    How old are you?
    "34"                 ; <== The function now returns immediately 
    

    【讨论】:

    • 谢谢。这是问题的正确答案,但我最终真正需要的是有点不同。请参阅下面的答案。
    • 能否请您也添加一个示例,因为您提供的链接也没有。
    【解决方案2】:

    这是我最终所做的示例代码。这个想法是一个简单的服务器读取/打印循环函数,它接受输入和输出流。我的问题是如何为这样的函数生成测试流,我认为字符串函数可以。相反,这正是我所需要的:

    (ns test
        (:use [clojure.java.io :only [reader writer]]))
    (def prompt ">")
    (defn test-client [in out]
      (binding [*in* (reader in)
                *out* (writer out)]
               (print prompt) (flush)
    
    (loop [input (read-line)]
                 (when input
                   (println (str "OUT:" input))
                   (print prompt) (flush)
                   (if (not= input "exit\n") (recur (read-line)) )
                   ))))
    (def client-stream (java.io.PipedWriter.))
    (def r (java.io.BufferedReader. (java.io.PipedReader. client-stream)))
    (doto (Thread. #(do (test-client r *out*))) .start)
    
    (.write client-stream "test\n")
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2014-05-02
      • 2016-11-24
      • 2022-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      相关资源
      最近更新 更多