Runtime.getRuntime().exec(cmd) hanging

后端 未结 2 1729
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 13:09

I am executing a command which returns me the Revision number of a file; \'fileName\'. But if there is some problem executing the command, then the application hangs up. Wha

2条回答
  •  难免孤独
    2020-12-01 13:54

    This code is based on the same idea Arham's answer, but is implemented using a java 8 parallel stream, which makes it a little more concise.

    public static String getOutputFromProgram(String program) throws IOException {
        Process proc = Runtime.getRuntime().exec(program);
        return Stream.of(proc.getErrorStream(), proc.getInputStream()).parallel().map((InputStream isForOutput) -> {
            StringBuilder output = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(isForOutput))) {
                String line;
                while ((line = br.readLine()) != null) {
                    output.append(line);
                    output.append("\n");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return output;
        }).collect(Collectors.joining());
    }
    

    You can call the method like this

    getOutputFromProgram("cmd /C si viewhistory --fields=revision --project="+fileName);
    

    Note that this method will hang if the program you are calling hangs, which will happen if it requires input.

提交回复
热议问题