目前很难将小型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()
调用,但没有成功。我总是看到正在启动命令的黑屏,但日志中没有任何内容......
任何帮助都会非常感激,我错过了一些东西,却无法理解...
答案 0 :(得分:1)
您不是在阅读您创建的流程的标准错误。
我怀疑正在向标准错误写入错误消息,并且因为您只是从标准输出读取,所以您没有收到此错误。
我建议您使用ProcessBuilder替换Runtime.getRuntime().exec(...)
的使用,使用以下内容:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "test.bat", "One", "Two");
pb.redirectErrorStream(true);
Process process = pb.start();
行pb.redirectErrorStream(true);
将进程的标准错误重定向到其标准输出,这样您就不必在两个独立的线程中读取两个流(标准输出和标准错误)。