目前无法将小型 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()
将输出重定向到日志文件的代码之前和之后进行调用,但没有成功。我总是看到正在启动的命令的黑屏,但日志中没有任何内容......
任何帮助将不胜感激,我遗漏了一些东西,但无法理解......