java执行bat命令碰到的阻塞问题的解决方法

事件起因:在Java中可以执行bat文件,有个需求需要执行bat文件才能完成,bat命令中会生成多个文件,在程序运行过程中我惊奇的发现,生成的文件在到一定数量时(当时是10个)就不再增加了,这远远的低于我设定的数量(100个),在我关闭程序后文件的数量又开始增加,我意识到可能是bat运行时被阻塞了,于是在网上查到的解决方案,就是以下这个,亲测可用!

工具类

public class StreamGobbler extends Thread {
    InputStream is;
    String type;
    OutputStream os;

    public StreamGobbler(InputStream is, String type) {
        this(is, type, null);
    }

    public StreamGobbler(InputStream is, String type, OutputStream redirect) {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }

    public void run() {
        InputStreamReader isr = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            if (os != null)
                pw = new PrintWriter(os);

            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (pw != null)
                    pw.println(line);
                System.out.println(type + ">" + line);//执行中输出的语句
            }

            if (pw != null)
                pw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (pw != null)
                    pw.close();
                br.close();
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

调用bat

Runtime rt = Runtime.getRuntime();
Process ps = null;
try {
    ps = rt.exec("cmd.exe /C start /b " + batDir);//batDir是bat文件路径
    //必要的,不然会阻塞
    StreamGobbler errorGobbler = new StreamGobbler(ps.getErrorStream(), "ERROR");
    errorGobbler.start();
    //好像没什么用
    StreamGobbler outGobbler = new StreamGobbler(ps.getInputStream(), "STDOUT");
    outGobbler.start();
   
    ps.waitFor();
} catch (Exception e1) {
    e1.printStackTrace();
}

int success = ps.exitValue();
if (success == 0) {
    //启动成功
} else {
    //启动失败
}

程序不会等待bat执行完成才接着执行,如果之后有代码要用到bat执行的结果需要自己添加判断


参考地址:https://www.jb51.net/article/46025.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值