从java执行批处理文件时行为不一致
我们的java方法执行一个批处理脚本,如下所示:从java执行批处理文件时行为不一致,java,batch-file,runtime.exec,Java,Batch File,Runtime.exec,我们的java方法执行一个批处理脚本,如下所示: String command = batchFilePath + File.separator + filename + " " + path; logger.info("Command to be executed = " + command); Process process = Runtime.getRuntime().exec(command); logger.info("Batchfile execution has started")
String command = batchFilePath + File.separator + filename + " " + path;
logger.info("Command to be executed = " + command);
Process process = Runtime.getRuntime().exec(command);
logger.info("Batchfile execution has started");
我们遇到了一种无法执行批处理文件的情况。但是,之前和之后的记录器语句都已正确记录。此外,上面的代码段位于try-catch块中,我们看到日志中没有记录任何异常。批处理文件执行另一个.exe文件,该文件的输出被写入一个单独的文件,而该文件也没有生成。在批处理文件中,我们有logger语句,以防.exe执行失败,但也没有错误
有人能帮我们确定为什么批处理文件没有执行,因为我们没有看到任何错误或异常。试试这个
您可以使用process.getErrorStream()
从流程中获取错误响应
您可以创建一个线程来不断地从错误流中读取,如下所示:
static class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type){
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ((line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public static void main(String[] args){
String command = batchFilePath + File.separator + filename + " " + path;
logger.info("Command to be executed = " + command);
Process process = Runtime.getRuntime().exec(command);
logger.info("Batchfile execution has started");
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
errorGobbler.start();
}
谢谢@Gagan,xtratic Ok,我会将上述逻辑添加到我的代码中以查找任何错误。值得一提的是,奇怪的是,如果我们在不更改命令或输入的情况下重新运行它,它会得到很好的执行。但是我们遇到了一些内存问题。我们正在检查是否是相关原因或其他原因造成的。不是我否决了这个。