EoF System.in 处理

EoF System.in processing

提问人:Oleg Boldov 提问时间:3/26/2022 更新时间:3/26/2022 访问量:254

问:

Scanner scanner=new Scanner(System.in);        

String s1=scanner.nextLine();         
String s2= scanner.nextLine();

我需要在第一次输入时写入 EoF(ctrl D)。我该如何处理它,以便 stdin 不会关闭并且我可以继续接收输入

Java 输入 EOF

评论


答:

1赞 Jim Garrison 3/26/2022 #1

你不能。达到 EOF 后,输入流将处于无效状态,无法进一步读取。

如果您需要发出类似于 EOF 的信号,但随后允许读取,则必须使用程序识别的一些特殊输入数据。

有一些丑陋的技巧可以防止 Ctrl+D 被识别为 EOF:如何在 EOF 之后重新打开 System.in 或完全阻止 EOF?另请参阅 https://stackoverflow.com/a/1066647/18157

评论

0赞 Oleg Boldov 3/26/2022
该程序有一个采用 Stdin 的循环。根据任务,如果用户按 ctrl+D,程序不应停止。怎么做?
1赞 that other guy 3/26/2022 #2

您可以简单地按照与原来相同的方式重新打开扫描仪:

import java.util.*;

class Foo {
  public static void main(String[] args) {
    Scanner scanner=new Scanner(System.in);
    System.err.println("Enter some text and hit some Ctr+D");
    while (true) {
      try {
        String s = scanner.nextLine();
        System.out.println("You wrote: " + s);
      } catch(NoSuchElementException e) {
        System.err.println("EOF. Retrying.");
        scanner = new Scanner(System.in);        // HERE
      }
    }
  }
}

请注意,如果流永久标记 EOF,例如在管道或重定向文件时,则这是一个无限循环,因此您有责任验证 stdin 是否为 tty 和/或添加重试限制。

评论

0赞 Oleg Boldov 3/26/2022
我插入了你的代码。如果它接受 ctrl D,它将无限期地输出错误消息。我需要将 EoF 视为 null 并继续处理输入。
0赞 that other guy 3/28/2022
确保直接在终端(其中 stdin 是 tty)中尝试,而不是在 IDE 的控制台窗口中尝试