在JAVA中运行.BAT文件而不打开命令提示符

时间:2014-10-28 00:34:15

标签: java

我一直在尝试使用以下行在Java中运行可执行.bat文件:

Runtime.getRuntime().exec("call " + batFile);

但它返回错误

  

无法使用commandLine启动进程nullCreateProcess:在此处调用 batfilename 错误= 2   IOException:Create Process:在此处调用 batfilename error = 2

我设法通过将String函数中的exec()替换为"cmd /c start " + batFile来绕过此问题,但这会打开一个不允许的命令提示符。

这有解决方法吗?谢谢!

2 个答案:

答案 0 :(得分:6)

尝试直接运行批处理文件,例如......

ProcessBuilder pb = new ProcessBuilder("C:/Test.bat");
pb.redirectError();
try {
    Process p = pb.start();
    try (InputStream inputStream = p.getInputStream()) {
        int in = -1;
        while ((in = inputStream.read()) != -1) {
            System.out.print((char)in);
        }
    }
    System.out.println("Exited with " + p.waitFor());
} catch (IOException | InterruptedException ex) {
    ex.printStackTrace();
}

这是批处理文件...

@echo Hello World

(我知道,大量)和输出的代码...

Hello World
Exited with 0

答案 1 :(得分:0)

有点晚了但是对于其他想要尝试的人我找到了启动命令的/ B.

(?:^|\s)((https?:\/\/)?(?:localhost|[\w-]+(?:\.[\w-]+)+)(:\d+)?(\/\S*)?)