Java键盘输入在控制台应用程序中解析 [英] Java keyboard input parsing in a console app

查看:255
本文介绍了Java键盘输入在控制台应用程序中解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 JLine 来解析控制台模式下的字符输入。它似乎运行良好,但我想知道:

I've just started messing around with JLine to parse character input in console mode. It seems to work well, but I'm wondering:

在JLine中是否有一种非阻塞方式来查明字符是否可用? (例如 kbhit() 。)

Is there a nonblocking way in JLine to find out if characters are available? (i.e. like kbhit() in Windows.)

我想我总是可以将键盘输入包装在自己的线程中,然后在线程中提供键盘字符 - 安全队列到主线程,但这似乎是不必要的。

I suppose I could always wrap keyboard input in its own thread which then offers the keyboard characters in a thread-safe queue to the main thread, but that seems like it should be unnecessary.

编辑:这是逐字符解析。我不打算使用GUI。在控制台模式下,Java中通常的InputStream I / O要求您首先按Enter键(例如,它只是缓冲输入)。请不要告诉我在控制台模式下逐个字符输入是不可能的;事实并非如此。 JLine使用具有平台相关实现的便携式接口来做到这一点。

EDIT: This is character-by-character parsing. I am not going to use a GUI. The usual InputStream I/O in Java in console mode requires you to hit the Enter key first (e.g. it's buffered input only). Please don't tell me character-by-character input in console mode is impossible in Java; it isn't. JLine does it using a portable interface with a platform-dependent implementation.

编辑更新:我能够将一个助手类组合在一起做工作线程中的阻塞I / O(对于每个字符的I / O使用JLine,警告:您必须自己解析Ctrl-C!)&然后通过同步队列与isempty()例程进行通信。对于我现在正在做的事情,这很好,但我真的想知道在未来做这件事的好方法。

Edit update: I was able to hack together a helper class to do the blocking I/O in a worker thread (using JLine for the per-character I/O, warning: you have to parse Ctrl-C yourself!) & then communicate via a synchronized queue with an isempty() routine. For what I'm doing right now that's fine, but I would really like to know a Good Way To Do This In The Future.

推荐答案

你似乎走在正确的轨道上。

You seem to be on the right track.

我认为这样做的正确方法是将所有阻塞I / O注入的工作线程非阻塞队列。 Hava了解 ConcurrentLinkedQueue 来自 java.util。并发

I think the "right" way to do this is a worker thread that pours all the blocking I/O into a non-blocking queue. Hava a look at ConcurrentLinkedQueue from java.util.concurrent.

这篇关于Java键盘输入在控制台应用程序中解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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