关于System.in和stream的问题

发布于 2024-10-19 04:26:34 字数 936 浏览 3 评论 0原文

有没有办法重置 System.in,以便我可以拥有一个新的流,让扫描仪等待输入?这是我的代码:

    boolean run = true;
    String commandLine = "";
    Scanner keyboard;

    Tokenizer arguments;
    RecursiveDescentParser parse;

    while (run){
        // Command prompt
        System.out.print(" ==>\t");

        keyboard = new Scanner(System.in);

        while (keyboard.hasNextLine()) {
              commandLine += " " + keyboard.nextLine();
        }

        keyboard.close();

        keyboard = null;

        System.setIn ( new FileInputStream ( FileDescriptor.in )  ) ;

        System.setIn(System.in);

        keyboard = new Scanner(System.in);

        arguments = new Tokenizer(commandLine);
        commandLine = "";
        parse = new RecursiveDescentParser(arguments, false);
        run = parse.parseStartSymbol();
    }           
} 

一旦这个程序运行一次, hasNextLine() 将无限期地返回 false ,提示一个问题我该如何解决这个问题?我可以以某种方式重置流吗?感谢您的帮助。

Is there a way to reset System.in so I can have a fresh stream from which to have Scanner wait for input? Here is my code:

    boolean run = true;
    String commandLine = "";
    Scanner keyboard;

    Tokenizer arguments;
    RecursiveDescentParser parse;

    while (run){
        // Command prompt
        System.out.print(" ==>\t");

        keyboard = new Scanner(System.in);

        while (keyboard.hasNextLine()) {
              commandLine += " " + keyboard.nextLine();
        }

        keyboard.close();

        keyboard = null;

        System.setIn ( new FileInputStream ( FileDescriptor.in )  ) ;

        System.setIn(System.in);

        keyboard = new Scanner(System.in);

        arguments = new Tokenizer(commandLine);
        commandLine = "";
        parse = new RecursiveDescentParser(arguments, false);
        run = parse.parseStartSymbol();
    }           
} 

Once this program has run once, hasNextLine() will return false indefinitely prompting a question how do I solve this? Can I reset the stream somehow? Thank you for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

就是爱搞怪 2024-10-26 04:26:34

我认为您正在寻找:

InputStream originalInput = System.in;
System.setIn(new FileInputStream(FileDescriptor.in));
// Do stuff
System.setIn(originalInput);

但是,最好不要替换 System.in,而只需让其余代码采用输入流即可使用。

I think you're looking for:

InputStream originalInput = System.in;
System.setIn(new FileInputStream(FileDescriptor.in));
// Do stuff
System.setIn(originalInput);

However, it would be a better idea never to replace System.in, and just make the rest of your code take an input stream to work with.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文