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

3

8

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 run in the background and not display the command line to the user. How can I change it to do this?

The problem is that the command window opens and intrupts the programs GUI. I just want the command window to not be visible while it is executing the batch file.

Ryun answered 9/7, 2012 at 11:46 Comment(1)
the problem is that the command window opens and intrupts the programs GUI. I just want the command window to not be visible while it is executing the batch file.Ryun
M
11

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).

Marital answered 9/7, 2012 at 11:56 Comment(3)
@developer I think not just tested in Windows 7 JDK 7 and it works fineMarital
i tested in windows xp, its not executing the command after i removed "start" from the above commandHogen
Well seems then it might be an XP thing, atleast now the OP will knowMarital
D
1

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.

Driven answered 9/7, 2012 at 11:52 Comment(0)
A
0
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.

Adenitis answered 9/7, 2012 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.