Execute command with prompt YES input
Asked Answered
G

2

7
 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

Germiston answered 5/10, 2015 at 12:29 Comment(2)
Can you give us an example like for an input string the expected behavior?Gherardo
If I get it...you want to use the value returned by p.waitFor() to say give a prompt Enter 'YES' to proceed:.Gherardo
C
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.

Corsage answered 5/10, 2015 at 12:41 Comment(5)
It is working fine on terminal but when I execute this command echo YES | pio app data-delete model in java , its not workedGermiston
I think it is due to pipeline character |Germiston
let me check, there might be a way to use runtime.exec() with composed commands.Corsage
done, for your information - #5928725Germiston
According to this post, you should either put the command in a script and execute it instead, or call a shell environment and pass it the commandCorsage
C
0

Do it like this:

line = reader.readLine();

if (line.toLowerCase().equals("yes")){
    ....
}
else if (line.toLowerCase().equals("no")){
    ....
}
else {
    ...
}
Collete answered 5/10, 2015 at 12:35 Comment(2)
I want to provide Yes or No as input so it can further execute the command. Command is not give YES or NOGermiston
please give us some more info in your questionCollete

© 2022 - 2024 — McMap. All rights reserved.