Java `BufferReader`在按下ENTER键之前不显示控制台输入(键入的)(仅在Windows&;Mac中,在Linux中工作)
我想以两种方式捕获用户输入,一种是不超时(等待到生命),另一种是在某个时间段内(如果时间超过/timeout,则应将其视为Java `BufferReader`在按下ENTER键之前不显示控制台输入(键入的)(仅在Windows&;Mac中,在Linux中工作),java,windows,input,bufferedreader,Java,Windows,Input,Bufferedreader,我想以两种方式捕获用户输入,一种是不超时(等待到生命),另一种是在某个时间段内(如果时间超过/timeout,则应将其视为null或无输入并继续)。所以我有这个密码 public class Main { public static void main(String[] args) { System.out.println("Type Something (timeout 5 Sec)"); /* Read input within
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;
}
}
}
它在键入时显示,但在超时后不会结束执行
(我不能使用
系统。请在超时时退出,对不起。)我真的很惊讶这在任何平台上都能正常工作。。。当System.in从控制台设备读取时。默认情况下,UNIX/Linux/BSD上的控制台设备(TTY)和虚拟控制台会进行行缓冲/编辑。@StephenC它在Linux上工作(更准确地说是ubuntu 20.04)。在Mac和Windows中,它的行为方式不同。请编辑代码,以便您可以复制粘贴整个代码段,并至少在Linux中尝试。就连我也对不同的行为感到困惑。
while (!buffer.ready()) {
Thread.sleep(5);
}