版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35529801/article/details/81013403
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Shell {
public static void main(String[] args) {
String command = "ls -l";
test(command);
}
public static void test(String command) {
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
process.getInputStream()));
String data = "";
while((data = reader.readLine()) != null) {
System.out.println(data);
}
int exitValue = process.waitFor();
if(exitValue != 0) {
System.out.println("error");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
Process exec(String command) :在一个单独的线程中执行此命令
waitFor()命令执行成功返回0,getInputStream()获取命令的输出
-
Process exec(String command)
-
在单独的进程中执行指定的字符串命令。