目前有两种方法:
方法一:Runtime.getRuntime().exec(String cmdarray[])
方法二:new ProcessBuilder(String... command).start()
首先在maven中导入:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
然后创建java程序:(博主是在macos上实验的)
package test_java;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunCmd {
public static void main(String[] args) {
//假设执行的命令是: /bin/sh -c ls -l
//方法1:
try {
String[] cmd = new String[]{"/bin/sh", "-c", "ls -l"};
Process ps = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
System.out.println("方法1:");
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
// 方法2:
try {
Process process = new ProcessBuilder("/bin/sh", "-c", "ls -l").start();
String s = IOUtils.toString(process.getInputStream(), "utf-8");
System.out.println("方法2:");
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
都可以打印结果:
方法1:
total 8
-rw-r--r-- 1 xq staff 781 Sep 21 20:34 pom.xml
drwxr-xr-x 4 xq staff 128 Sep 21 11:01 src
drwxr-xr-x 4 xq staff 128 Sep 21 20:44 target
方法2:
total 8
-rw-r--r-- 1 xq staff 781 Sep 21 20:34 pom.xml
drwxr-xr-x 4 xq staff 128 Sep 21 11:01 src
drwxr-xr-x 4 xq staff 128 Sep 21 20:44 target