之前一直在用
Process process = Runtime.getRuntime().exec(cmd);
後來發現有的時候好像不那麼好用,嘗試使用下面的方式感覺更好用一些。
import java.io.*;
public class ProcessTest {
public static void main(String[] args) {
String[] command1 = new String[]{"/bin/sh", "-c", "ls -l /tmp"};
test1(command1);
}
public static void test1(String[] cmd) {
try {
ProcessBuilder builder = new ProcessBuilder(cmd);
Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String content = br.readLine();
while (content != null) {
System.out.println(content);
content = br.readLine();
}
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}
}
}