首页 > 解决方案 > Java 在没有构建器的情况下启动 CMD 和多个命令

问题描述

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

在以下示例中,我尝试使用不起作用的 BufferedWriter.write。预先感谢您的回答。

主.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;
    }

}

标签: javacmdruntime.execbufferedwriter

解决方案


使用 Runtime.getRuntime().exec(String command),您可以使用条件运算符从单个命令行或脚本运行多个命令。

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

推荐阅读