简体   繁体   中英

Executing command in terminal from java programmatically

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.

There are a number of problems with your code:

  • keytool sends its prompts to stderr , not stdout , so you need to call proc.getErrorStream()
  • You don't want to buffer the output from keytool as you need to see the prompts
  • You don't want to wait for keytool to terminate
  • As 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());
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM