打开一个新的命令提示符,并从在命令提示符下运行的Java程序发送命令

时间:2018-06-22 14:31:30

标签: java command-prompt processbuilder

我有一个在命令提示符(A)中运行的Java程序,想打开一个新的命令提示符(B),在B中运行一些命令,然后关闭B命令提示符窗口。

我一直在使用这些帖子作为参考:

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

这是我的代码:

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();
    }

上面的代码打开一个新的命令提示符(B),但是在此新命令提示符(B)中均未输入任何命令。当前的Java程序只是挂在命令提示符(A)中。

我知道我缺少一些命令和参数,以使过程完成时关闭命令提示符(B)。

有没有更好的方法来构建它?

感谢您的帮助。

0 个答案:

没有答案