Java进程调用比较简单,但这里有些细节需要注意:当我们使用

Runtime.getRuntime().exec()

这段代码时,通常情况下是没有没问题的,但某些程序的异常信息太多,如果没对异常信息处理,很容易就会造成缓冲区溢出,导致进程阻塞。笔者这里提供一个简单粗暴的方法:

public static Process runProcess(String script, String[] params, String inPath,final Boolean isOutput) {
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(script, params, new File(inPath));
			final InputStream is1 = process.getInputStream();
			final InputStream is2 = process.getErrorStream();
			new Thread(() -> {
				try {
					BufferedReader in = new BufferedReader(new InputStreamReader(is2, Charset.forName("GBK")), 20480);
					String str;
					while ((str = in.readLine()) != null) {
						if (isOutput) {
							System.out.println(str);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}).start();
			new Thread(() -> {
				try {
					BufferedReader in = new BufferedReader(new InputStreamReader(is1, Charset.forName("GBK")), 20480);
					String str;
					while ((str = in.readLine()) != null) {
						if (isOutput) {
							System.out.println(str);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return process;
	}

值得注意的是:该方法是异步执行,如果您要同步执行,移除掉第二个

new Thread(() -> {})

即可。