6
 public static String executeCommand(String command) {
    StringBuffer sb = new StringBuffer();
    Process p;
    try {
      p = Runtime.getRuntime().exec(command);
      p.waitFor();
     }   BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line = "";
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return sb.toString();
}

given code is working fine to execute any command but I have a command which want YES/NO as input. How I can give the input to command for further execution?

ex.

executeCommand("pio app data-delete model");

output-
[INFO] [App$] Data of the following app (default channel only) will be deleted. Are you sure?
[INFO] [App$]     App Name: twittermodeling
[INFO] [App$]       App ID: 14
[INFO] [App$]  Description: None
Enter 'YES' to proceed:

So How I can give YES to them for further execution.

Thanks

Kishore
  • 5,761
  • 5
  • 28
  • 53
  • 1
    Can you give us an example like for an input string the expected behavior? – Tirath Oct 05 '15 at 12:32
  • If I get it...you want to use the value returned by `p.waitFor()` to say give a prompt `Enter 'YES' to proceed:`. – Tirath Oct 05 '15 at 12:44

2 Answers2

4

If you really need to pass "YES" to an unix command, you could prefix it by echo YES |. echo YES | pio app data-delete model should force deletion.

In the context of runtime.exec() thought the pipe can't be evaluated correctly, refer to this post for more information.

However, the first thing you should do is check if the pio command does not have a "force" flag, usually -f, which would omit user interactions.

Community
  • 1
  • 1
Aaron
  • 24,009
  • 2
  • 33
  • 57
  • It is working fine on terminal but when I execute this command echo YES | pio app data-delete model in java , its not worked – Kishore Oct 05 '15 at 12:56
  • I think it is due to pipeline character | – Kishore Oct 05 '15 at 12:56
  • let me check, there might be a way to use runtime.exec() with composed commands. – Aaron Oct 05 '15 at 12:56
  • done, for your information - http://stackoverflow.com/questions/5928225/how-to-make-pipes-work-with-runtime-exec – Kishore Oct 05 '15 at 13:00
  • According to [this post](http://stackoverflow.com/questions/5928225/how-to-make-pipes-work-with-runtime-exec), you should either put the command in a script and execute it instead, or call a shell environment and pass it the command – Aaron Oct 05 '15 at 13:00
0

Do it like this:

line = reader.readLine();

if (line.toLowerCase().equals("yes")){
    ....
}
else if (line.toLowerCase().equals("no")){
    ....
}
else {
    ...
}
roeygol
  • 4,908
  • 9
  • 51
  • 88