0%

java调用执行外部程序

文章字数: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();
}
}