开发者

Sending Multiple Inputs to a Command with exec

开发者 https://www.devze.com 2023-04-02 08:13 出处:网络
I need to execute a command at the command line and a series of Yes or No answers need to be provided after the command is executed.

I need to execute a command at the command line and a series of Yes or No answers need to be provided after the command is executed. For example:


>./somecommand (return)

Are you sure about this? [yes/no]: yes (return)

Are you really sure about this? [yes/no]: yes (return)

Last chance. [yes/no]: no (retur开发者_如何学Gon)

OK.


I'm trying to use the following code snippet to accomplish this task.

try {
   // Execute command
   String command = "somecommand";
   Process child = Runtime.getRuntime().exec(command);

   // Get output stream to write from it
   OutputStream out = child.getOutputStream();

   out.write("yes".getBytes());

   out.flush();      
   out = child.getOutputStream();
   out.write( "yes".getBytes() );

   out.flush();      
   out = child.getOutputStream();
   out.write( "no".getBytes() );

   out.close();
} catch (IOException e) {
}

As you can see, I tried using 'out = child.getOutputStream()' three times, flushing 'out' after each write. But that didn't seem to work. Any idea how this could be done?


Try the java readLine() command in a while loop. Give it a terminating condition like Yes or No.

0

精彩评论

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