java implementation of the solution blocking problems encountered bat command

Cause of the incident: when can execute bat file in Java, there is a need to execute bat file needs to be completed, bat command will generate multiple files, I was surprised to find that the program is running, the resulting file in a certain amount (at the time is 10) no longer increases, which is far lower than the amount I set (100), the number of files increased again after I close the program, I realized that may have been blocked bat runtime, so the solution found on the internet, this is the following, pro-test available!

Tools

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();
            }
        }
    }
}

Call 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 {
    //启动失败
}

The program does not wait for execution to complete before then execute bat, if you have code to use after the implementation of the results of bat needs to add their own judgment


Reference Address: https://www.jb51.net/article/46025.htm

Guess you like

Origin blog.csdn.net/rui15111/article/details/84029958