How do I run command line from Java code in the background?

前端 未结 3 2031
一向
一向 2021-01-02 11:53

I have the following line to run a batch file,

Process process = Runtime.getRuntime().exec(\"cmd /c start rake.bat\");

But I want it to ru

相关标签:
3条回答
  • 2021-01-02 12:03

    I'm not quite sure what you mean by 'in the background'

    If you mean simply that the window isn't visible, this SO answer may be of use.

    If (however) you mean that you want your Java program to continue running whilst this executes, then you should spawn this off in a separate thread.

    Regardless of the above, be careful to capture your batch file's sdtout/stderr.

    0 讨论(0)
  • 2021-01-02 12:12

    Removing the 'start' completely will do what you want (as this is what is creating the window):

    Process process = Runtime.getRuntime().exec("cmd /c rake.bat");
    

    I have tested this and it works, ofcourse if you want to communicate with the command prompt you'd have to have Input and Output streams, also not forgetting your Error stream As stated in the comment though removing 'start' on XP wont help (as it wont work).

    0 讨论(0)
  • 2021-01-02 12:21
    Process process = Runtime.getRuntime().exec("cmd /c start rake.bat");
    

    If you are calling the above line from a java process to execute the batch file. This will by default run in background.

    0 讨论(0)
提交回复
热议问题