Java ProcessBuilder输出到字符串

时间:2015-07-01 08:04:48

标签: java processbuilder

如何重定向或将系统输出转换为String?

tracker.on(...

2 个答案:

答案 0 :(得分:1)

以下是关于如何将系统命令进程的标准输出捕获到字符串容器中的意见。

Adapted from the web:

try {
  ProcessBuilder pb = new ProcessBuilder("echo", "dummy io");
  final Process p=pb.start();
  BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
  String line;
  StringBuilder sb = new StringBuilder();
  while((line=br.readLine())!=null) sb.append(line);
}

System.out.println(sb.toString());

答案 1 :(得分:0)

与我最初评论基本I / O的一个好例子一致。我删除了一些代码,除了基本功能之外还有一些功能。

<强>附加功能

  • 变量的环境shell和
  • 工作目录

这些功能为系统命令添加了“profile-style”执行。

基础工作

Oracle的

Java ThreadingJoining

<强>代码

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by triston on 11/2/17.
 */

public class Commander {

  private Commander(){} // no construction

  public static class StreamHandler implements Runnable {

    Object source;
    Object destination;

    StreamHandler(Object source, Object oDestination) {
      this.source = source; this.destination = oDestination;
    }

    public void run() {
      if (source instanceof InputStream) {
        BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) source));
        String line;
        try {
          while ((line = br.readLine()) != null) ((StringBuilder) destination).append(line + '\n');
        } catch (IOException oE) {
        }
      } else {
        PrintWriter pw = new PrintWriter((OutputStream)destination);
        pw.print((String)source);
        pw.flush(); pw.close();
      }
    }

    public static Thread read(InputStream source, StringBuilder dest) {
      Thread thread = new Thread(new StreamHandler(source, dest));
      (thread).start();
      return thread;
    }

    public static Thread write(String source, OutputStream dest) {
      Thread thread = new Thread(new StreamHandler(source, dest));
      (thread).start();
      return thread;
    }

  }

  static Map<String, String> environment = loadEnvironment();

  static String workingDirectory = ".";

  static Map<String, String> loadEnvironment() {
    ProcessBuilder x = new ProcessBuilder();
    return x.environment();
  }

  static public void resetEnvironment() {
    environment = loadEnvironment();
    workingDirectory = ".";
  }

  static public void loadEnvirons(HashMap input) {
    environment.putAll(input);
  }

  static public String getEnviron(String name) {
    return environment.get(name);
  }

  static public void setEnviron(String name, String value) {
    environment.put(name, value);
  }

  static public boolean clearEnviron(String name) {
    return environment.remove(name) != null;
  }

  static public boolean setWorkingDirectory(String path) {
    File test = new File(path);
    if (!test.isDirectory()) return false;
    workingDirectory = path;
    return true;
  }

  static public String getWorkingDirectory() {
    return workingDirectory;
  }

  static public class Command {

    ProcessBuilder processBuilder = new ProcessBuilder();
    Process process;

    public Command(String... parameters) {
      processBuilder.environment().putAll(environment);
      processBuilder.directory(new File(workingDirectory));
      processBuilder.command(parameters);
    }

    public int start(String input, StringBuilder output, StringBuilder error) throws IOException {

      // start the process
      process = processBuilder.start();

      // start the error reader
      Thread errorBranch = StreamHandler.read(process.getErrorStream(), error);

      // start the output reader
      Thread outputBranch = StreamHandler.read(process.getInputStream(), output);

      // start the input
      Thread inputBranch = StreamHandler.write(input, process.getOutputStream());

      int rValue = 254;
      try {
        inputBranch.join(); rValue--;
        outputBranch.join(); rValue--;
        errorBranch.join(); rValue--;
        return process.waitFor();
      } catch (InterruptedException oE) {
        oE.printStackTrace();
        return rValue;
      }

  }

}

<强>测试

@Test public void foo() {
  Command cmd = new Command("sh", "--");
  StringBuilder output = new StringBuilder();
  StringBuilder error = new StringBuilder();
  int pValue = 127;
  try {
    pValue = cmd.start("echo well done > /dev/stderr\n\necho oh, wow; false", output, error);
  } catch (IOException oE) {
  }
  System.out.println("output: "+output.toString());
  System.out.println("error: "+error.toString());
  System.out.println("\nExit code: "+pValue);
  System.exit(pValue);
}

带上您自己的packageJUnit注释。此示例代码演示了返回值,命令输入,命令标准输出和命令错误输出。

我的原创设计,要求主线程执行标准输出处理。

度过美好的一天。