0
try
{
    Runtime rt =  Runtime.getRuntime();
    rt.exec("cmd /c start cmd.exe /K \"java -version\"");
    System.out.println("After completing the first command");
    rt.exec("cmd /c start cmd.exe /K \"javac -version\""); 
}
catch (Exception e)
{
    System.out.println("Something wrong");
    e.printStackTrace();
}

By using the above program I am able to execute commands in a terminal, but it opens multiple instances of the terminal. I want to execute both commands in the same terminal. Is this possible?

3
  • 1
    I'm not a MS Windows genius but you start multiple command prompts with start cmd.exe or? Commented Apr 23, 2018 at 13:42
  • Can't you simply write a batch that executes the 2 commands one after the other? From within your JVM you should then simply launch that batch. Commented Apr 23, 2018 at 13:44
  • Have you leaned about Thread objects? Commented Apr 23, 2018 at 14:13

3 Answers 3

2

As suggested, you can put your commands in a .bat file that you will run from java program or you can use the & or the && operator.

(The difference between the two operators is that && will let the second command be executed only if the first succeeded.)

Try this:

rt.exec("cmd /c start cmd.exe /K \"java -version && javac -version\"");
Sign up to request clarification or add additional context in comments.

3 Comments

"cmd /c start cmd.exe" isn't really necessary if you want to run in the existing cmd session
yes that can be done by using && operator. but i just wanted some operations before executing second command. after performing some operations i want to execute second command in the previously opened command line.
@Chandrakanth, why don't you start your Java app in a terminal and just print the result in a standard output?
1

You could also use a ProcessBuilder java API to do this. By default Runtime.getRuntime().exec will tokenize the input, in the case of ProcessBuilder it will execute the command as it is.

public class TestCommands {

    public static void main(String[] args) throws IOException, InterruptedException {

        String[] commands = {"echo hello","echo hi","java -version"};

        for(String command : commands) {
            execute(command);
        }
    }


    public static void execute(String command) throws InterruptedException, IOException {
        ProcessBuilder builder = new ProcessBuilder("cmd.exe","/c",command);
        Process process = builder.inheritIO().start();
        process.waitFor();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String readline;
        while ((readline = reader.readLine()) != null) {
            System.out.println(readline);
        }
    }
}

1 Comment

I've tried this code in a unit test, but the output is going to my output screen, not the BufferedReader. Do you know why this is?
0

If anyone is looking for a solution for macOS, I made one:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CustomDesktop {
    public static void main(String[] args) throws IOException, InterruptedException {
        // Execute multiple commands in one terminal.
        final String[] TERMINAL_COMMANDS = {"cd ~/Videos", "ls -l"};

        StringBuilder command = new StringBuilder(); // Using StringBuilder is recommended: less memory and faster.
        for (String terminalCommand : TERMINAL_COMMANDS) {
            command.append(terminalCommand).append(';');
        }
        execute(command.toString());

        // Direct method call, if you prefer.
        execute("cd ~/Videos; ls -l");
    }

    public static void execute(String command) throws IOException, InterruptedException {
        // Use "bash" instead if your Mac runs pre-Catalina.
        ProcessBuilder builder = new ProcessBuilder("zsh", "-c", command);
        Process process = builder.inheritIO().start();
        process.waitFor();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String readline;
        while ((readline = reader.readLine()) != null) {
            System.out.println(readline);
        }
    }
}

Output:

total 539296
-rw-r--r--@ 1 macintoshfan  staff  276116282 Jun 18 14:14 Java.mov
total 539296
-rw-r--r--@ 1 macintoshfan  staff  276116282 Jun 18 14:14 Java.mov

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.