Issue
I want to execute a command from Java but this command wants me to give it a username.
Like this example:
$ my command
[command] Username:_
So how can I give the command my username in Java?
Currently my code is like this:
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while ((s = br.readLine()) != null){
System.out.println(s);
}
br.close();
p.waitFor();
p.destroy();
Solution
You need to create another thread and pump user input through process#getOutputStream()
. See the following example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class ProcessWithInput {
public static void main(String[] args) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("cat");
OutputStream os = p.getOutputStream();
os.write("Hello World".getBytes());
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
p.waitFor();
p.destroy();
}
}
Ofcourse, you need to do proper error/exception handling etc.
Other option is to use ProcessBuilder
which allows you to provide input through a File.
Answered By - Dakshinamurthy Karra