如何将ProcessBuilder的输出重定向到字符串?

2022-08-31 12:29:36

我正在使用以下代码来启动流程构建器。我想知道如何将它的输出重定向到.String

ProcessBuilder pb = new ProcessBuilder(
    System.getProperty("user.dir") + "/src/generate_list.sh", filename);
Process p = pb.start();

我尝试使用,但它似乎不起作用。ByteArrayOutputStream


答案 1

从 中读取 .您可以将输出追加到 :InputStreamStringBuilder

BufferedReader reader = 
                new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
   builder.append(line);
   builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();

答案 2

使用Apache Commons IOUtils,你可以用一行话来做:

ProcessBuilder pb = new ProcessBuilder("pwd");
String output = IOUtils.toString(pb.start().getInputStream(), StandardCharsets.UTF_8);

推荐