ProcessBuilder 在多次执行批处理文件时抛出 IO 异常

问题描述 投票:0回答:0

我正在尝试使用 Processbuilder 从我的 Java 应用程序运行一个批处理文件,并使用一个 API 来调用这个 Processbuilder。当我第一次运行 api 时,Processbuilder 能够找到批处理文件,然后它正在执行预期的操作。但是当我第二次运行 api 而没有弹出应用程序时,我得到了一个 IO 异常:

java.io.IOException: Cannot run program "I:/test/test.bat": The system cannot find the path specified

这就是我的代码的样子 服务层:

@Override
public String submitRequest() {
    List<String> command = new ArrayList<>();
    String scriptPath = "I:\\test\\test.bat";
    command.add(scriptPath);
    int exitCode= runCommandWithLog(logFilePath,command);
}

 public int runCommandWithLog(String logFile, List<String> command)  {
    int exitCode = -1;
    try{
        logger.info("Running the batch file located at {}", command.get(0));
        ProcessBuilder pb =  new ProcessBuilder(command)
                .redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFile + ".log")))
                .redirectError( ProcessBuilder.Redirect.appendTo(new File(logFile + ".err")));

        Process p = pb.start();
        logger.info("Starting the batch file with the logger function");

        p.getInputStream().close();
        p.getOutputStream().close();
        p.getErrorStream().close();

        p.waitFor(15, TimeUnit.MINUTES);
        exitCode = p.exitValue();
        p.destroy();
        
        logger.info("Process has been destroyed");
        logger.info("Exit Code for the Execution {}" ,exitCode);
    }catch (Exception e){
        e.printStackTrace();
    }
    return exitCode;
}

PS堆栈跟踪:

java.io.IOException: Cannot run program "I:/test/test.bat": The system cannot find the path specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at com.jpmc.ct.tcio.securities.service.impl.ShellSeriveImpl.runCommandWithLog(ShellSeriveImpl.java:90)
    at com.jpmc.ct.tcio.securities.service.impl.ShellSeriveImpl$ConsumerWorkerThread.run(ShellSeriveImpl.java:141)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.io.IOException: The system cannot find the path specified
    at java.base/java.lang.ProcessImpl.openForAtomicAppend(Native Method)
    at java.base/java.lang.ProcessImpl.newFileOutputStream(ProcessImpl.java:81)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:135)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
    ... 9 more
java batch-file process processbuilder
© www.soinside.com 2019 - 2024. All rights reserved.