开发者

Question about System.in and stream

开发者 https://www.devze.com 2023-02-13 03:38 出处:网络
Is there a way to reset System.in so I can have a fresh stream fr开发者_开发技巧om which to have Scanner wait for input? Here is my code:

Is there a way to reset System.in so I can have a fresh stream fr开发者_开发技巧om 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号