Running bat file with java processbuilder

微笑、不失礼 提交于 2019-12-10 09:49:30

问题


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 envoirnment when I replace file.bat with ./file.sh

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);
} 

回答1:


First element in array must be an executable. So you have to invoke cmd.exe in order to call you batch file.

ProcessBuilder builder = new ProcessBuilder(Arrays.asList(new String[] {"cmd.exe", "/C", WORKING_DIR + File.separator + "file.bat"}));



回答2:


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:

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);
} 


来源:https://stackoverflow.com/questions/17120782/running-bat-file-with-java-processbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!