Java在不使用生成器的情况下启动CMD和多个命令

Java在不使用生成器的情况下启动CMD和多个命令,java,cmd,runtime.exec,bufferedwriter,Java,Cmd,Runtime.exec,Bufferedwriter,我想知道是否有办法在java应用程序和CMD的一个窗口之间建立某种“链接”,在那里我可以单独发布多个命令->而无需构建器。假设必须计算下一个命令,但将其推送到同一个CMD窗口中 在下面的示例中,我尝试使用BufferedWriter.write,但它不起作用。 提前感谢您的回答 Main.java import java.io.IOException; public class Main { public static void main(String[] args) throws

我想知道是否有办法在java应用程序和CMD的一个窗口之间建立某种“链接”,在那里我可以单独发布多个命令->而无需构建器。假设必须计算下一个命令,但将其推送到同一个CMD窗口中

在下面的示例中,我尝试使用BufferedWriter.write,但它不起作用。 提前感谢您的回答

Main.java

import java.io.IOException;

public class Main {

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

        CmdProcess cmdProcess = new CmdProcess();

        cmdProcess.executeCmdCommand("echo Hello World");
        // I do not want to post commands together
        cmdProcess.executeCmdCommand("ping localhost");
    }
}
CmdProcess.java

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class CmdProcess {

    public CmdProcess() throws IOException {
        startUpProcess();
    }

    private Process cmd;
    private BufferedWriter writer;

    private void startUpProcess() throws IOException {
        String startCommand = "cmd.exe /c start ";
//        init CMD
        try {
            setCmd(Runtime.getRuntime().exec(startCommand));
        } catch (IOException e) {
            System.err.println(e.toString());
            throw new IOException("Not able to launch CMD in CmdProcess.startUpProcess().");
        }
//        init writer
        writer = new BufferedWriter(new OutputStreamWriter(getCmd().getOutputStream()));
    }

    public void executeCmdCommand(String command) throws IOException {
        writer.write(command);
        writer.flush();
    }

    public Process getCmd() {
        return cmd;
    }

    public void setCmd(Process cmd) {
        this.cmd = cmd;
    }

}

使用Runtime.getRuntime.execString命令,可以使用条件运算符从单个命令行或脚本运行多个命令

command1 & command2 - Executes comand1 and then command2
command1 && command2 - 2nd command executes if 1st command exeutes successfully

你可以参考嘿,谢谢回复。这真的很高兴知道,无论如何,我正在寻找一种方法,我不使用单一的命令行或脚本,但我可以分别发送多个命令。有办法吗?你觉得怎么样?为什么不使用ProcessBuilder并传递命令列表?假设我需要发布一些命令并根据结果发送一个或另一个。我想要java端的逻辑,因为我想要使用DB数据。我不想为cmd准备几个场景脚本。