process两种用法(1)
process两种用法(一)
package interview.process; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class ProcessUsual { public static void main(String[] args) { call("javac"); call("cmd.exe /C dir"); } public static void call(String cmd) { Runtime rt = Runtime.getRuntime(); Process pro = null; try { pro = rt.exec(cmd); // =======在waitfor之前必须调用这两个方法======// new StreamTool(pro.getInputStream()).start(); new StreamTool(pro.getErrorStream()).start(); // ===================================// pro.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(pro.exitValue()); } private static class StreamTool extends Thread { BufferedReader br = null; public StreamTool(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public void run() { String line = null; try { while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } }