How to pipe a string argument to an executable launched with Apache Commons Exec?

前端 未结 2 1373
梦毁少年i
梦毁少年i 2020-12-16 18:43

I need to pipe a text argument to the stdin of a command launched with Apache Commons Exec (for the curious, the command is gpg and the argument is the passphrase to the key

2条回答
  •  盖世英雄少女心
    2020-12-16 19:00

    Hi to do this i will use a little helper class like this: https://github.com/Macilias/Utils/blob/master/ShellUtils.java

    basically you can than simulate the pipe usage like shown here before without calling the bash beforehand:

    public static String runCommand(String command, Optional dir) throws IOException {
        String[] commands = command.split("\\|");
        ByteArrayOutputStream output = null;
        for (String cmd : commands) {
            output = runSubCommand(output != null ? new ByteArrayInputStream(output.toByteArray()) : null, cmd.trim(), dir);
        }
        return output != null ? output.toString() : null;
    }
    
    private static ByteArrayOutputStream runSubCommand(ByteArrayInputStream input, String command, Optional dir) throws IOException {
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        CommandLine cmd = CommandLine.parse(command);
        DefaultExecutor exec = new DefaultExecutor();
        if (dir.isPresent()) {
            exec.setWorkingDirectory(dir.get());
        }
        PumpStreamHandler streamHandler = new PumpStreamHandler(output, output, input);
        exec.setStreamHandler(streamHandler);
        exec.execute(cmd);
        return output;
    }
    

提交回复
热议问题