Start with ProcessBuilder
. Each parameter you want to send the command is a separate element in the command list, for example...
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder(
"whiptail", "--title", "Check list example", " --checklist",
"Choose user's permissions", "20", "78", "4",
"NET_OUTBOUND", "Allow connections to other hosts", "ON",
"NET_INBOUND", "Allow connections from other hosts", "OFF",
"LOCAL_MOUNT", "Allow mounting of local devices", "OFF",
"REMOTE_MOUNT", "Allow mounting of remote devices", "OFF");
pb.redirectInput(Redirect.INHERIT);
// I tend to use pb.redirectErrorStream(true);
// which sends the error stream to the input stream, but
// then you'd need to still consume it to get the result
Process p = pb.start();
InputStreamConsumer errorConsumer = new InputStreamConsumer(p.getErrorStream());
Scanner input = new Scanner(System.in);
String option = input.nextLine();
p.getOutputStream().write(option.getBytes());
p.getOutputStream().flush();
int exitCode = p.waitFor();
System.out.println(exitCode);
errorConsumer.join();
System.out.println(errorConsumer.getContent());
}
public static class InputStreamConsumer extends Thread {
private InputStream is;
private StringBuilder content;
public InputStreamConsumer(InputStream is) {
this.is = is;
content = new StringBuilder(128);
}
public String getContent() {
return content.toString();
}
@Override
public void run() {
try {
int value = -1;
while ((value = is.read()) != -1) {
content.append((char)value);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}
This is very basic, it simply executes the command, consumes it's output into a StringBuilder
(to be retrieved later), waits till the command exists and displays the basic results.
Since I don't have access to whiptail
, I can't test the code, but if the command is available in the default search path of the OS, it should work, otherwise you'll need to supply the path to the command as part of the first element in the command list