1

目前无法将小型 Windows 批处理控制台的输出重定向到日志文件。我的 Java 应用程序需要启动 Runtime.exec() 调用而不等待它完成并仍然记录输出。这是我的记录器类:

public class BatchThreadLogger extends Thread {
  private Process process;
  private String logFilePath;
  private static final Logger logger = Logger.getLogger(BatchThreadLogger.class);

  public BatchThreadLogger(Process process, String logFilePath) {
    this.process = process;
    this.logFilePath = logFilePath;
  }

  public void run() {
    try {
      // create logging file
      File file = new File(logFilePath);
      file.createNewFile();

      // create a writer object
      OutputStream os = new FileOutputStream(file);
      PrintWriter pw = new PrintWriter(os);

      // catch the process output in an InputStream
      InputStreamReader isr = new InputStreamReader(process.getInputStream());
      BufferedReader br = new BufferedReader(isr);

      // wait for the process to complete
      int processStatus = process.waitFor();

      // redirect the output to the log file
      String line = null;
      while ((line = br.readLine()) != null) {
        pw.println(line);
      }

      // add a small message with the return code to the log
      pw.println("********************************************");
      pw.println("********************************************");
      pw.println("Batch call completed with return status " + processStatus);

      pw.flush();
      os.close();
    }
    catch (IOException e) {
      logger.error("IOException raised during batch logging on file " + logFilePath, e);
    }
    catch (InterruptedException e) {
      logger.error("InterruptedException raised during batch process execution", e);
    }
  }
}

我的电话很简单:

Process process = Runtime.getRuntime().exec(command);
BatchThreadLogger logger = new BatchThreadLogger(process, logFilePath);
logger.start();

我的命令目前只是用两个参数调用我的 test.bat。我的测试批次现在只做:

echo "BATCH CALLED WITH PARAMETER %1 AND %2"
exit

但是,我的日志文件仅包含:

********************************************
********************************************
Batch call completed with return status 0

我试图在waitFor()将输出重定向到日志文件的代码之前和之后进行调用,但没有成功。我总是看到正在启动的命令的黑屏,但日志中没有任何内容......

任何帮助将不胜感激,我遗漏了一些东西,但无法理解......

4

1 回答 1

1

您没有从您创建的流程的标准错误中读取。

I suspect that an error message is being written to the standard error, and because you're only reading from standard output, you're not picking up this error.

I would recommend replacing your use of Runtime.getRuntime().exec(...) with a ProcessBuilder, using something like the following:

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "test.bat", "One", "Two");
pb.redirectErrorStream(true);
Process process = pb.start();

The line pb.redirectErrorStream(true); redirects the process' standard error into its standard output, so that you don't have to read from two streams (standard output and standard error) in two separate threads.

于 2012-06-05T11:01:25.967 回答