Reputation: 5962
I have a requirement to execute a command in terminal using java. I am really stuck up to access terminal window of mac through java code programmatically. It would be really useful if you provide your valuable solutions to perform my task which i have been struggling to do for a past two days. I am also posting the piece of code that I am trying to do for your reference. Any kind of help would be helpful for me
public class TerminalScript
{
public static void main(String args[]){
try {
Process proc = Runtime.getRuntime().exec("/Users/xxxx/Desktop/NewFolder/keytool -genkey -v -keystore test.keystore -alias test -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000");
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Note: I have to run the command keytool -genkey -v -keystore test.keystore -alias test -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000
in terminal through java program.
Upvotes: 0
Views: 1090
Reputation: 2689
There are a number of problems with your code:
keytool
sends its prompts to stderr
, not stdout
, so you need to call proc.getErrorStream()
keytool
as you need to see the promptskeytool
to terminate keytool
is interactive, you need to read from and write to the process. It might be better to spawn separate threads to handle the input and output separately.The following code addresses the first three points as a proof of concept and will show the first prompt from keytool, but as @etan-reisner says, you probably want to use the native APIs instead.
Process proc = Runtime.getRuntime().exec("/usr/bin/keytool -genkey -v -keystore test.keystore -alias test -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000");
InputStream read = proc.getErrorStream();
while (true) {
System.out.print((char)read.read());
}
Upvotes: 2