在 java 中打印时阻止控制台接受输入?

Preventing console from taking input while printing in java?

我在使用我制作的方法时遇到了问题。它从文本文件中读取,并延迟将内容打印到控制台上,但是,在打印时它可以随机获取用户的输入。有时它会与打印的内容交织在一起。有更好的方法吗?

public static void filePrint(String location) throws IOException, FileNotFoundException, InterruptedException {
        
        File flScannedFile = new File(location);
        
        Scanner scFileScanner = new Scanner(flScannedFile);
        
        while (scFileScanner.hasNext()) {
    
            String file = scFileScanner.nextLine();
                        
            System.out.print(file);
            
            Thread.sleep(650);
        }
    }

IDE 上的用户将始终能够在控制台上书写,我想这就是您遇到的情况。睡眠时间长这一事实使您清楚地看到了这一点。但是,即使用户在控制台上写任何东西,也不应该影响全局输出。

我想补充的一件事是,您可能希望将打印切换为 println;而且,最好使用 try and catch 而不是在方法名称上列出所有这些异常 :)