How to open Terminal and execute command using jav

2019-09-06 15:10发布

问题:

How to launch terminal and execute some commands using java code in MAC?

Similar question i have found for LINUX OS from below link.

how to run a command at terminal from java program?

回答1:

It worked same as Linux,

Runtime.getRuntime().exec("rm filename");

Thanks @ginz



回答2:

You need to run it using bash executable like this:

Runtime.getRuntime().exec("/bin/bash -c **YouTerminalSoftWareName**");

YouTerminalSoftWareName must be absolute path or aready in your PATH environment variable



回答3:

Use Apple Script Editor to open Terminal and run your code.

For Example :

String action1 = jsonDriver.readApplicationDetails("OFF");
Runtime runtime = Runtime.getRuntime();
String applescriptCommand = "tell application \"Terminal\"\n" + 
         "activate\n" + "delay 1\n" + "tell application \"System Events\"\n" + 
         "keystroke \"" + action1 + "\"\n" + "end tell\n" + "end tell"; 
String[] args1 = { "osascript", "-e", applescriptCommand };
Process process = runtime.exec(args1);
Thread.sleep(5000);