我无法捕获 我的 Java 命令行应用程序中的击键。使用 System.in.read() 当按下 Tab 键时我似乎没有得到任何东西。解决这个问题的最佳方法是什么?
为了提供一些上下文,我试图允许用户在命令中间按 Tab 键以使其自动完成命令(就像您在 bash shell 中所做的那样)。如果有更好的方法来实现这一点,我愿意接受建议(也许使用 System.in.read() 不是实现这一点的最佳角度?)。
I'm having trouble capturing the <tab> keystroke in my Java command-line application. Using System.in.read() I don't seem to get anything when hitting the tab key. What is the best way to approach this?
To give some context, I'm trying to allow a user to hit the tab key mid-command to have it autocomplete the command (much like you might do in a bash shell). I'm open to suggestions if there are better approaches to achieving this (perhaps using System.in.read() isn't the best angle to approach this?).
发布评论
评论(3)
看看 JLine。我自己没用过。它使用 Windows DLL(使用 JNI),并且具有 Linux 支持,可以将控制台切换到字符/原始模式而不是缓冲模式。我以前从未使用过这个,所以使用时需要您自担风险。我也不是 100% 确定它是否能解决您的问题,但值得一试:)
编辑:我可以确认它确实有效
再次编辑:该库确实包含命令行的自动完成(通过按 Tab 键)...享受吧:)
Have a look at JLine. I have not used it myself. It uses a windows DLL (using JNI) and it has linux support to switch the console to character/raw mode instead of buffered mode. I have never used this before so use at your own risk. I am also not 100% sure if it will address your issue, but its worth a shot :)
EDIT: I can confirm it does work
EDIT AGAIN: The library does contain autocomplete (by pressing tab) for the command line... Enjoy :)
仅当用户按下 Enter 键时,InputStream 中的数据才可用。我想你会发现如果你在选项卡后按 Enter 键,选项卡就会显示出来。
在 C 应用程序中,有类似的情况:shell 将输入模式从熟的设置为原始,因为它需要原始击键。 Readline 是 Linux 中用于此目的的普通库。我不确定 Windows 上有什么常见的。据我所知,使用 JNI 是唯一的选择。
Data from an InputStream is only made available when the user has pressed enter. I think you'll find that if you press enter after tab, the tab will show up.
In c applications, there is something similar: a shell sets the input mode to raw from cooked, since it needs the raw keystrokes. Readline is the normal library used for this in Linux. I'm not sure what's common on Windows. As far as I can think, something using JNI is the only option here.
我猜想您的 shell 正在捕获选项卡并阻止它访问您的应用程序。对此你可能无能为力......
I would guess that your shell is capturing tab and preventing it from getting to your application. There may not be anything you can do about this...