简体   繁体   中英

Separating System.Out messages and Scanner (Java)

Is there a way, without using a gui package of any sort, to not have System.out inject itself into the middle of your prompt?

The scenario is a threaded program where you send and receive messages to a server.

While writing to the server, you get a message from the server.

"I'm writinMESSAGE FROM SERVERg a message"

So you basically end up seeing something like that in your console.

Is there a way to circumvent this problem and essentially separate the prompt from the input?

You can do something like this to buffer output temporary:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream oldOut = System.out;
    System.setOut(new PrintStream(out));

    // System.in read code

    System.setOut(oldOut);
    System.out.println(out.toString());

Same for System.err

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM