參見:https://blog.csdn.net/lixingshi/article/details/50467840
public static void runtimeCommand() throws Exception { Process process = Runtime.getRuntime().exec("cmd.exe /c dir"); int status = process.waitFor(); System.out.println(status); InputStream in = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = br.readLine(); while(line!=null) { System.out.println(line); line = br.readLine(); } }
命令行中使用/c關閉執行完畢的窗口,否則無法獲取輸入流。但是在Linux下面就可以直接使用如下代碼獲取輸入流:
Process process = Runtime.getRuntime().exec("ls"); int status = process.waitFor(); System.out.println(status); InputStream in = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = br.readLine(); while(line!=null) { System.out.println(line); line = br.readLine(); }
還可以使用ProcessBuilder進行創建進程,這種方更靈活。代碼如下:
public static void processBuilderCommand() throws Exception { List<String> commands = new ArrayList<>(); commands.add("cmd.exe"); commands.add("/c"); commands.add("dir"); commands.add("E:\\flink"); ProcessBuilder pb =new ProcessBuilder(commands); //可以修改進程環境變量 pb.environment().put("DAXIN_HOME", "/home/daxin"); System.out.println(pb.directory()); Process process = pb.start(); int status = process.waitFor(); System.out.println(pb.environment()); System.out.println(status); InputStream in = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = br.readLine(); while(line!=null) { System.out.println(line); line = br.readLine(); } }
調用java命令執行class文件並獲取輸出:
public static void processBuilderCommand() throws Exception { List<String> commands = new ArrayList<>(); commands.add("cmd.exe"); commands.add("/c"); commands.add("java HelloWorld"); ProcessBuilder pb =new ProcessBuilder(commands); pb.directory(new File("C:\\Users\\liuguangxin\\oxygen--workspace\\java8\\bin\\"));//設置工作目錄 Process process = pb.start(); int status = process.waitFor(); InputStream in = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = br.readLine(); while(line!=null) { System.out.println(line); line = br.readLine(); } }
java C:\\Users\\liuguangxin\\oxygen--workspace\\java8\\bin\\HelloWorld會將目錄作為類名一起解析故無法執行。