Java Process with Input/Output Stream

后端 未结 3 1376
我在风中等你
我在风中等你 2020-11-22 01:23

I have the following code example below. Whereby you can enter a command to the bash shell i.e. echo test and have the result echo\'d back. However, after the f

3条回答
  •  你的背包
    2020-11-22 02:09

    I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:

    Thread T=new Thread(new Runnable() {
    
        @Override
        public void run() {
            while(true)
            {
                String input = scan.nextLine();
                input += "\n";
                try {
                    writer.write(input);
                    writer.flush();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
    
        }
    } );
    T.start();
    

    and you can reader will be same as above i.e.

    while ((line = reader.readLine ()) != null) {
        System.out.println ("Stdout: " + line);
    }
    

    make your writer as final otherwise it wont be able to accessible by inner class.

提交回复
热议问题