如何解决在按下ENTER键之前,“ BufferReader”不显示控制台输入已键入仅在Windows和Mac中,在Linux中有效
我想用两种方法来捕获用户输入,一种是在一段时间内没有超时(一直等到寿命结束),另一种是在一段时间内(如果时间超出/超时,则应视为null
或无输入并继续前进)。所以我有这段代码。
public class Main {
public static void main(String[] args) {
System.out.println("Type Something (timeout 5 Sec)");
/* Read input within 5 Sec or done,whichever happens first*/
String inputTimeOut = executeInTime(Main::readInput,5,TimeUnit.SECONDS);
System.out.println("TimeOut Inupt Given: " + inputTimeOut);
System.out.println("Type Something");
/* Read Input without time restriction */
String input = readInput();
System.out.println("Inupt Given: " + input);
}
public static String executeInTime(Callable<String> call,long wait,TimeUnit unit) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> task = executorService.submit(call);
String input = null;
try {
input = task.get(wait,unit);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
task.cancel(true);
} finally {
executorService.shutdown();
}
return input;
}
public static String readInput() {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
try {
while (!buffer.ready()) {
Thread.sleep(5);
}
String input = buffer.readLine();
return input;
} catch (IOException | InterruptedException e) {
return null;
}
}
}
在Linux上运行正常。同样在Wondows中,结束行为是相同的,但是存在一个小问题。 在Windows / Mac中,直到按Enter键,我才能看到到目前为止输入的内容。在Linux(Ubuntu)中,我键入后就会出现。
有人知道为什么它在Windows中表现不同吗?只要允许读取操作可中断/可杀死且通用(例如我的readInput()
),其他任何解决方案都将受到欢迎。
更新:
如果我对此发表评论
while (!buffer.ready()) {
Thread.sleep(5);
}
它在键入时显示,但在超时后没有结束执行。
(抱歉,我无法使用System.exit
。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。