控制台应用程序中的 Java 键盘输入解析

2023-05-04Java开发问题
13

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

问题描述

限时送ChatGPT账号..

我刚刚开始使用 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() 在 Windows 中.)

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.

EDIT:这是逐个字符的解析.我不会使用 GUI.Java 中控制台模式下通常的 InputStream I/O 要求您先按 Enter 键(例如,它只是缓冲输入).请不要告诉我在控制台模式下逐个字符输入在 Java 中是不可能的;不是.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(使用 JLine 进行每个字符的 I/O,警告:你必须自己解析 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.

推荐答案

你似乎走对了.

我认为执行此操作的正确"方法是使用工作线程将所有阻塞 I/O 倒入非阻塞队列中.看看 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 键盘输入解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13