Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Java, run multiple commands in the same cmd.exe window

I'm developing a Java application that will be run on a Windows computer occasionally. At some point I need to run a Cygwin prompt and performs some commands in it.

I've found a topic where the Runtime class is used: http://www.javaquery.com/2011/03/how-to-execute-multiple-command-in.html

However it doesn't launch a real cmd.exe window, it's only run in background and the output is just printed on the Eclipse console.

I'm looking for a solution to run a real cmd.exe window and I need to pass as many commands as I want to that windows shell. Is this possible?

like image 225
singe3 Avatar asked Nov 04 '25 17:11

singe3


2 Answers

This one works... using && operator you can add one or commands to be executed in same command prompt

try {
    Process p = Runtime
                    .getRuntime()
                    .exec("cmd /c start cmd.exe /K \"dir && ping localhost && echo end\"");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

Consider the solution in here also

Update from the questioner: Solution to execute commands in cygwin

getRuntime().exec("cmd /c start C:/cygwin64/bin/bash.exe --login -c \"ls ; whoami ; exec bash\"");
like image 177
AJJ Avatar answered Nov 07 '25 10:11

AJJ


If you do not need to show a console on the screen, that is easy. You have some simple steps to follow :

  • start a Process via `Process cmd = new ProcessBuilder("cmd.exe").start();
  • send your commands to cmd.getOutputStream()
  • read the result of the commands from cmd.getInputStream() and/or cmd.getErrorStream()
  • when finished with it close cmd.getOutputStream(), and if necessary kill the process by cmd.destroy()

Optionnaly, you can have output and error stream to be merged :

Process cmd = new ProcessBuilder("cmd.exe").redirectErrorStream(true).start();

then you simply ignore cmd.getErrorStream() and only read from cmd.getInputStream()

like image 29
Serge Ballesta Avatar answered Nov 07 '25 11:11

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!