Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open the command prompt and insert commands using Java?

Is it possible to open the command prompt (and I guess any other terminal for other systems), and execute commands in the newly opened window?

Currently what I have is this:

Runtime rt = Runtime.getRuntime(); rt.exec(new String[]{"cmd.exe","/c","start"}); 

I've tried adding the next command after the "start", I've tried running another rt.exec containing my command, but I can't find a way to make it work.

If it matters, I'm trying to run a command similar to this:

java -flag -flag -cp terminal-based-program.jar 

EDIT Unfortunately I have had some strange findings. I've been able to successfully launch the command prompt and pass a command using this:

rt.exec("cmd.exe /c start command"); 

However, it only seems to work with one command. Because, if I try to use the command separator like this, "cmd.exe /c start command&command2", the second command is passed through the background (the way it would if I just used rt.exec("command2");). Now the problem here is, I realized that I need to change the directory the command prompt is running in, because if I just use the full path to the jar file, the jar file incorrectly reads the data from the command prompt's active directory, not the jar's directory which contains its resources.

like image 428
404 Not Found Avatar asked Jan 14 '11 05:01

404 Not Found


People also ask

What is Command Prompt in Java?

While many programming environments allow us to compile and run a program within the environment, we can also compile and run java programs using Command Prompt. After successful installation of JDK in our system and set the path, we can able to compile and execute Java programs using the command prompt.

How do I open the command prompt?

Open Command Prompt in Windows 10Move the mouse pointer to the bottom-left corner of the screen and Right-click, or press Windows key + X. In the power user task menu, select Command Prompt (Admin) (Figure 8). This will open the Command Prompt window (Figure 9).


1 Answers

I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.

rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\""); 
like image 89
404 Not Found Avatar answered Sep 30 '22 02:09

404 Not Found