0
public class Controller {

public String printResults(Process process) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = "";
    String container = "";
    while ((line = reader.readLine()) != null) {
        container = container + line + "\n";
        System.out.println(line);
    }
    return container;
}

public String executeCmd(String firstname,  String lastname) throws IOException {
    
    String command = "./myprogram -n " + firstname + " -s " + lastname;
    Process p = Runtime.getRuntime().exec(command, null, new File("/home/user/myprogram/build/"));
    return "Hi, \n" + printResults(p);
}
}

This allowes me to run a single command with attributes from a specific directory and get back result.

However, I have a larger program, which asks user for inputs from terminal.

user@debian:~/program/build/$./program
...
Enter Value: 5
...
Enter Name: Hanz
...
Enter State: GE

Output..

How can I run that program and enter user input from Java?

1
  • Building a command as a string -- in any programming language -- is a fast route to serious security problems. The underlying OS interface on UNIX -- execve -- uses an array of strings; your code should do the same. Otherwise, you need to worry about whether you have, say, a firstname of $(rm -rf ~) Commented Nov 9, 2020 at 23:15

1 Answer 1

1

First, rewrite your code to use ProcessBuilder; it's pretty much just replacing exec with new ProcessBuilder.

That's because PB gives you some flexibility that may well come up. For example, you can redirect inputs and outputs to files, for example.

Then, run start() on the builder and this gets you a Process object. You can use this to get the OutputStream, and then you can write your string to that: p.getOutputStream().write("5\nHanz\GE".getBytes());

There are a couple of different ways to do the job; Have a look at the APIs of Process and ProcessBuilder, there's lots of interesting stuff in there :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.