想必遇到这个问题的朋友,查过很多了,网上主要的办法貌似有3.
第一:就是新建两个线程处理输入输出流。这个办法比较好理解,也比较通用,比较通用。
第二:还有关闭对输入输出流的输入。这个不太通用,在处理文件的的时候貌似好使。
第三:通过获取process的输出流,根据一个while循环判断console中的内容来做处理。
第一:就是新建两个线程处理输入输出流。这个办法比较好理解,也比较通用,比较通用。
第二:还有关闭对输入输出流的输入。这个不太通用,在处理文件的的时候貌似好使。
第三:通过获取process的输出流,根据一个while循环判断console中的内容来做处理。
我这里主要介绍第一种,我也是网上找了一个可用的实例。下面是一个工具类:
package com.project.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CommandUtil {
// 保存进程的输入流信息
private List<String> stdoutList = new ArrayList<String>();
// 保存进程的错误流信息
private List<String> erroroutList = new ArrayList<String>();
public void executeCommand(String command) {
// 先清空
stdoutList.clear();
erroroutList.clear();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
// 创建2个线程,分别读取输入流缓冲区和错误流缓冲区
ThreadUtil stdoutUtil = new ThreadUtil(p.getInputStream(), stdoutList);
ThreadUtil erroroutUtil = new ThreadUtil(p.getErrorStream(), erroroutList);
//启动线程读取缓冲区数据
stdoutUtil.start();
erroroutUtil.start();
p.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public List<String> getStdoutList() {
return stdoutList;
}
public List<String> getErroroutList() {
return erroroutList;
}
}
class ThreadUtil implements Runnable {
// 设置读取的字符编码
private String character = "GB2312";
private List<String> list;
private InputStream inputStream;
public ThreadUtil(InputStream inputStream, List<String> list) {
this.inputStream = inputStream;
this.list = list;
}
public void start() {
Thread thread = new Thread(this);
thread.setDaemon(true);//将其设置为守护线程
thread.start();
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream, character));
String line = null;
while ((line = br.readLine()) != null) {
if (line != null) {
list.add(line);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//释放资源
inputStream.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
下面是测试方法。参数可以使直接的dos命令,也可以是一个bat脚本的绝对路径。
public static void test(String str) {
CommandUtil util = new CommandUtil();
util.executeCommand(str);
printList(util.getStdoutList());
System.out.println("--------------------");
printList(util.getErroroutList());
}
public static void printList(List<String> list){
for (String string : list) {
System.out.println(string);
}
}