Get process output without blocking

前端 未结 2 2050
粉色の甜心
粉色の甜心 2021-01-22 08:14

I want to get a process\' output (Git.exe to be exact) and convert it to a String object. Previously sometimes my code was blocked. Then I figured out that it\'s be

2条回答
  •  隐瞒了意图╮
    2021-01-22 08:54

    Using this beautiful article and the StreamGobbler class described there (which I modified a little) I solved the problem. My implementation of StreamGobbler:

    class StreamGobbler extends Thread {
        InputStream is;
        String output;
    
        StreamGobbler(InputStream is) {
            this.is = is;
        }
    
        public String getOutput() {
            return output;
        }
    
        public void run() {
            try {
                StringWriter writer = new StringWriter();
                IOUtils.copy(is, writer);
                output = writer.toString();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    

    and my function is:

    public static String runProcess(String executable, String parameter) {
        try {
            String path = String.format("%s %s", executable, parameter);
            Process pr = Runtime.getRuntime().exec(path);
    
            StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream());
            StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream());
    
            // kick them off concurrently
            errorGobbler.start();
            outputGobbler.start();
    
            pr.waitFor();
            return outputGobbler.getOutput();
        } catch (Exception e) {
            return null;
        }
    }
    

提交回复
热议问题