3

I have a Java program running in a command prompt (A) and would like to open a new command prompt (B), run some commands in B, and then close the B command prompt window.

I have been using these posts as reference:

Create a new cmd.exe window from within another cmd.exe prompt

How to open a command prompt and input different commands from a java program

I was able to open a command prompt from my Java program, How to run some exe in this command prompt using java code?

pass multiple parameters to ProcessBuilder with a space

Start CMD by using ProcessBuilder

Here is my code:

public static void startCMD(String appName) {
        // init shell       
        String[] cmd = new String[]{"cmd.exe", "/C", "start"};      
        ProcessBuilder builder = new ProcessBuilder(cmd);
        Process p = null;
        try {
            p = builder.start();
        } catch (IOException e) {
            System.out.println(e);
        }
        // get stdin of shell
        BufferedWriter p_stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

        // execute the desired command (here: ls) n times
        try {
            // single execution
            p_stdin.write("C:");
            p_stdin.newLine();
            p_stdin.flush();

            p_stdin.write("cd C:\\" + appName);
            p_stdin.newLine();
            p_stdin.flush();

            p_stdin.write("sbt \"run 8080\"");
            p_stdin.newLine();
            p_stdin.flush();

        } catch (IOException e) {
            System.out.println(e);
        }

        // finally close the shell by execution exit command
        try {
            p_stdin.write("exit");
            p_stdin.newLine();
            p_stdin.flush();
        } catch (IOException e) {
            System.out.println(e);
        }

        // write stdout of shell (=output of all commands)
        Scanner s = new Scanner(p.getInputStream());
        while (s.hasNext()) {
            System.out.println(s.next());
        }
        s.close();
    }

The code above opens a new command prompt (B), but none of the commands are entered in this new command prompt (B). The current Java program just hangs in the command prompt (A).

I know I am missing some commands and parameters to have the command prompt (B) to close when the process is finished.

Is there a better way to build this?

I appreciate the help.

0

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.