使用 java processbuilder 运行 bat 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17120782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running bat file with java processbuilder
提问by Salman Raza
I am trying to execute .bat file using java process builder but it does not starts the process. Please tell me what i am doing wrong here. This code works fine with linux envtheitroadnment when I replace file.bat with ./file.sh
我正在尝试使用 java 进程构建器执行 .bat 文件,但它没有启动进程。请告诉我我在这里做错了什么。当我用 ./file.sh 替换 file.bat 时,此代码适用于 linux 环境
final ArrayList<String> command = new ArrayList<String>();
command.add(WORKING_DIR+File.separator+"file.bat");
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.redirectErrorStream(true);
builder.start();
} catch (IOException e) {
logger.error("Could not start process." ,e);
}
回答by Toilal
First element in array must be an executable. So you have to invoke cmd.exe in order to call you batch file.
数组中的第一个元素必须是可执行文件。所以你必须调用 cmd.exe 才能调用你的批处理文件。
ProcessBuilder builder = new ProcessBuilder(Arrays.asList(new String[] {"cmd.exe", "/C", WORKING_DIR + File.separator + "file.bat"}));
回答by Juned Ahsan
Make sure the path to the bat file is correct. You can either debug it using a debugger or put a sysout to determine that:
确保bat文件的路径正确。您可以使用调试器对其进行调试,也可以使用 sysout 来确定:
final ArrayList<String> command = new ArrayList<String>();
System.out.println("Batch file path : " + WORKING_DIR+File.separator+"file.bat")
command.add(WORKING_DIR+File.separator+"file.bat");
final ProcessBuilder builder = new ProcessBuilder(command);
try {
builder.redirectErrorStream(true);
builder.start();
} catch (IOException e) {
logger.error("Could not start process." ,e);
}