Java – Send Parameter To Runtime.getRuntime().exec() After Execution

javaprocessruntime

I need to execute a command in my java program but after executing the command , it required another parameter ( a password in my case ). how can I manage the output process of Runtime.getRuntime().exec() to accept parameter for further execution ?

I tried new BufferedWriter(new OutputStreamWriter(signingProcess.getOutputStream())).write("123456"); but it did not work.

Best Solution

Does your program not feature a --password option ? Normally all command line based programs do, mainly for scripts.

Runtime.getRuntime().exec(new String[]{"your-program", "--password="+pwd, "some-more-options"});

Or the more complicated way and much more error-prone:

try {
    final Process process = Runtime.getRuntime().exec(
            new String[] { "your-program", "some-more-parameters" });
    if (process != null) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DataInputStream in = new DataInputStream(
                            process.getInputStream());
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(in));
                    String line;
                    while ((line = br.readLine()) != null) {
                        // handle input here ... ->
                        // if(line.equals("Enter Password:")) { ... }
                    }
                    in.close();
                } catch (Exception e) {
                    // handle exception here ...
                }
            }
        }).start();
    }
    process.waitFor();
    if (process.exitValue() == 0) {
        // process exited ...
    } else {
        // process failed ...
    }
} catch (Exception ex) {
    // handle exception
}

This sample opens a new thread (keep in mind concurrency and synchronisation) that's going to read the output of your process. Similar you can feed your process with input as long as it has not terminated:

if (process != null) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                DataOutputStream out = new DataOutputStream(
                        process.getOutputStream());
                BufferedWriter bw = new BufferedWriter(
                        new OutputStreamWriter(out));
                bw.write("feed your process with data ...");
                bw.write("feed your process with data ...");
                out.close();
            } catch (Exception e) {
                // handle exception here ...
            }
        }
    }).start();
}

Hope this helps.