How do I run a batch file from my Java Application?

后端 未结 11 1676
情书的邮戳
情书的邮戳 2020-11-22 00:42

In my Java application, I want to run a batch file that calls \"scons -Q implicit-deps-changed build\\file_load_type export\\file_load_type\"

It seems t

相关标签:
11条回答
  • 2020-11-22 01:08

    The executable used to run batch scripts is cmd.exe which uses the /c flag to specify the name of the batch file to run:

    Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});
    

    Theoretically you should also be able to run Scons in this manner, though I haven't tested this:

    Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});
    

    EDIT: Amara, you say that this isn't working. The error you listed is the error you'd get when running Java from a Cygwin terminal on a Windows box; is this what you're doing? The problem with that is that Windows and Cygwin have different paths, so the Windows version of Java won't find the scons executable on your Cygwin path. I can explain further if this turns out to be your problem.

    0 讨论(0)
  • 2020-11-22 01:09

    Batch files are not an executable. They need an application to run them (i.e. cmd).

    On UNIX, the script file has shebang (#!) at the start of a file to specify the program that executes it. Double-clicking in Windows is performed by Windows Explorer. CreateProcess does not know anything about that.

    Runtime.
       getRuntime().
       exec("cmd /c start \"\" build.bat");
    

    Note: With the start \"\" command, a separate command window will be opened with a blank title and any output from the batch file will be displayed there. It should also work with just `cmd /c build.bat", in which case the output can be read from the sub-process in Java if desired.

    0 讨论(0)
  • 2020-11-22 01:09

    This code will execute two commands.bat that exist in the path C:/folders/folder.

    Runtime.getRuntime().exec("cd C:/folders/folder & call commands.bat");
    
    0 讨论(0)
  • 2020-11-22 01:14

    To run batch files using java if that's you're talking about...

    String path="cmd /c start d:\\sample\\sample.bat";
    Runtime rn=Runtime.getRuntime();
    Process pr=rn.exec(path);`
    

    This should do it.

    0 讨论(0)
  • 2020-11-22 01:17
    Process p = Runtime.getRuntime().exec( 
      new String[]{"cmd", "/C", "orgreg.bat"},
      null, 
      new File("D://TEST//home//libs//"));
    

    tested with jdk1.5 and jdk1.6

    This was working fine for me, hope it helps others too. to get this i have struggled more days. :(

    0 讨论(0)
  • 2020-11-22 01:17

    The following is working fine:

    String path="cmd /c start d:\\sample\\sample.bat";
    Runtime rn=Runtime.getRuntime();
    Process pr=rn.exec(path);
    
    0 讨论(0)
提交回复
热议问题