0

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 (return)

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mohammad Najar
  • 2,009
  • 2
  • 21
  • 31
  • check the following post: http://stackoverflow.com/questions/2877609/in-java-send-commands-to-another-command-line-program –  Sep 01 '11 at 17:22
  • Does `somecommand` have an `--assume-yes` or similar option? – trashgod Sep 01 '11 at 18:52
  • No .. I need to capture the question the process outputs and based on that provide an answer to the question. – Mohammad Najar Sep 01 '11 at 19:20

1 Answers1

1

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

Mike Vince
  • 26
  • 4