从java调用批处理需要从当前批处理文件文件夹启动



我正在从我的java程序中启动一个批处理文件,它将停止一些tomcat,如果它将从命令行启动,批处理本身就可以工作。但是从java开始它不工作,问题是批处理不会从它所在的文件夹调用。所以它找不到一些文件,我的问题是我如何切换到批处理所在的文件夹,然后启动批处理,以便它从其文件夹运行,并找到必要的文件。

例如,批处理位于文件夹c:foobarmybatch。cmd

下面是我的代码,当前批处理将从java

调用
public void startBatch(Path batchPath) {
    if (batchPath == null) {
        throw new IllegalArgumentException("cannot start batch without path to it");
    }
    if (!Files.exists(batchPath)){
        throw new IllegalArgumentException("batch does not exist " + batchPath.toString());
    }
    try {
        log.info("starting batch " + batchPath.toAbsolutePath().toString());
        String command = "cmd.exe /c " + batchPath.toAbsolutePath().toString();
        Process p;
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            log.info(line);
            line = reader.readLine();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // TODO Auto-generated method stub
}

你应该把cd c:foobar放到批处理文件中。

最新更新