java - 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;
}
}
解决方案
使用 Runtime.getRuntime().exec(String command),您可以使用条件运算符从单个命令行或脚本运行多个命令。
command1 & command2 - Executes comand1 and then command2
command1 && command2 - 2nd command executes if 1st command exeutes successfully
推荐阅读
- python - 我想在文件中找到第一个空白行并在其中写入文本但它不会写入?
- spring - 在使用 Spring Azure OAuth 时从不同来源加载用户角色
- ascii-art - Ascii艺术动画文件格式?
- laravel - 如何使路线模型绑定与我需要的任何路线一起运行?
- r - 根据另一列中的条件跨多列执行函数
- ios - 无法使通用链接工作
- html - 如何在使用 css 网格时优化大量 ng-repeats
- c# - 接收 POST 请求但从未调用的操作方法
- java - 为什么某些 Java 函数能够更改不可变的 Kotlin 对象?
- vim - 在 vim 中的文件级别设置拼写检查字典