gpt4 book ai didi

java - 使用 Java 将系统调用输出重定向到文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:54 25 4
gpt4 key购买 nike

当前将小型 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() 调用,但没有成功。我总是看到正在启动的命令黑屏,但日志中没有任何内容...

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

最佳答案

您没有读取您创建的进程的标准错误。

我怀疑错误消息正在被写入标准错误,并且因为您仅从标准输出读取,所以您没有发现此错误。

我建议您将 Runtime.getRuntime().exec(...) 的使用替换为 ProcessBuilder ,使用类似以下内容:

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

pb.redirectErrorStream(true);将进程的标准错误重定向到其标准输出,这样您就不必在两个单独的线程中读取两个流(标准输出和标准错误)。

关于java - 使用 Java 将系统调用输出重定向到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10894608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com