单个字符控制台输入在java / clojure中 [英] Single character console input in java/clojure

查看:194
本文介绍了单个字符控制台输入在java / clojure中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从控制台读取单个字符/键,而无需按Enter键? Sun的错误数据库中有旧条目,声称它可以' t在纯java。我找到了这些方法

How can I read a single character/key from the console without having to hit Enter? There is an old entry in Sun's bug database claiming that it can't be done in pure java. I've found these approaches

  • JNI
  • JLine [http://jline.sourceforge.net/]
  • Javacurses [http://sourceforge.net/projects/javacurses/]

我希望在我的类路径中添加一个 magic-readkey.jar ,并写几行代码,例如(def just-hit(com.acme.MagicConsole / read-char))

I'd expect to add a single magic-readkey.jar to my classpath, and to write a few lines of code, like (def just-hit (com.acme.MagicConsole/read-char)).

推荐答案

这里是一个使用JLine的立即回显应用程序,将打印对应于注册按键的 int ,结构化为 Leiningen project:

Here's an "immediate echo" app using JLine which will print ints corresponding to registered keypresses, structured as a Leiningen project:


  1. project.clj

(defproject con "1.0.0-SNAPSHOT"
  :description "FIXME: write"
  :main con.core
  :dependencies [[org.clojure/clojure "1.1.0"]
                 [org.clojure/clojure-contrib "1.1.0"]
                 [jline "0.9.94"]])


  • src / con / core.clj

    (ns con.core
      (:import jline.Terminal)
      (:gen-class))
    
    (defn -main [& args]
      (let [term (Terminal/getTerminal)]
        (while true
          (println (.readCharacter term System/in)))))
    


  • 有问题的功能由 jline.Terminal 类,它提供了一个静态方法 getTerminal 返回一个平台特定子类的实例,可用于与终端进行交互。有关详情,请参阅 Javadoc

    The functionality in question is provided by the jline.Terminal class, which provides a static method getTerminal returning an instance of a platform-specific subclass which can be used to interact with the terminal. See the Javadoc for more details.

    让我们看看 asdf 看起来像...

    Let's see what asdf looks like...

    $ java -jar con-1.0.0-SNAPSHOT-standalone.jar 
    97
    115
    100
    102
    

    Cc 当然会杀死应用程式。)

    (C-c still kills the app, of course.)

    这篇关于单个字符控制台输入在java / clojure中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆