文章字数:89,阅读全文大约需要1分钟
java调用外部程序可以使用Runtime.getRuntime().exec()
,他会调用一个新的进程去执行。
使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class ExecTest { public static void main(String[] args) throws IOException, InterruptedException { String cmd = "cmd /c dir c:\\windows"; final Process process = Runtime.getRuntime().exec(cmd); printMessage(process.getInputStream()); printMessage(process.getErrorStream()); int value = process.waitFor(); System.out.println(value); } private static void printMessage(final InputStream input) { new Thread(new Runnable() { public void run() { Reader reader = new InputStreamReader(input); BufferedReader bf = new BufferedReader(reader); String line = null; try { while((line=bf.readLine())!=null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } }
|