/**
* Copyright (C) 2017-2018 All Rights Reserved.
*/
package processdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class RuntimeDemo {
public static void main(String[] args) throws IOException, InterruptedException {
/**
* Process + Runtime
* Runtime的exec執(zhí)行函數(shù)也是調(diào)用的ProcessBuilder的構(gòu)造函數(shù)來創(chuàng)建子進(jìn)程并執(zhí)行
*/
Runtime runtime = Runtime.getRuntime();
//新啟一個(gè)子進(jìn)程
Process process = runtime.exec("pwd");
//子進(jìn)程向主進(jìn)程輸出信息
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp = null;
while( (temp = bufferedReader.readLine()) != null){
System.out.println(temp);
}
/**
* Process + ProecssBuilder
*/
List<String> cmdList = Arrays.asList("ls","-a");
ProcessBuilder processBuilder = new ProcessBuilder(cmdList);
process = processBuilder.start();
//waitFor()函數(shù)是讓當(dāng)前主進(jìn)程等待該子進(jìn)程執(zhí)行完畢,正常退出則返回0
if(process.waitFor() != 0 )
System.exit(1);
//子進(jìn)程向主進(jìn)程輸出信息
inputStream = process.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while( (temp = bufferedReader.readLine()) != null){
System.out.println(temp);
}
}
}
Runtime是程序運(yùn)行時(shí)環(huán)境忘蟹,不能new一個(gè)Runtime對象斗塘,只能通過getRuntime()方式獲取Runtim運(yùn)行時(shí)對象的引用欣舵。
Runtime+Process 和 ProcessBuilder+Process的區(qū)別就是運(yùn)行子進(jìn)程的命令不相同。