cmd如何在不单独启动的情况下作为java程序的一部分使用



我想创建一个java程序,它可以接受用户的输入,并将该输入传递给cmd,然后获取并显示输出给用户。我在互联网上见过很多例子,但它们只告诉我们如何从外部启动cmd。但我不想启动cmd。我想把cmd作为程序的一部分,这样它就不会打开,只会像在输入上执行一些无形的操作并返回输出一样工作。有人能说出来吗?

此外,我几乎没有尝试在这个网站上搜索类似的问题,但没有找到。如果是重复的,很抱歉。

您可以使用Runtime#exec。以下片段显示了如何读取cmd.exe中执行的某个命令的输出。

public static String executeCommand(String command) throws IOException
{
StringBuilder outputBuilder = new StringBuilder();
Process process = Runtime.getRuntime().exec(new String[] {"cmd", "/c", command});
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String read = null;
while((read = outputReader.readLine()) != null)
{
outputBuilder.append(read).append("n");
}
outputReader.close();
process.destroy();
return outputBuilder.toString();
}

以下示例显示了如何与进程进行交互通信。

public static void main(String[] args) throws Exception {
Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", "cmd" /* Replace with the name of the executable */});
Scanner scanner = new Scanner(System.in);
PrintWriter printWriter = new PrintWriter(process.getOutputStream());
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
new Thread(() -> {
try {
String read = null;
while ((read = outputReader.readLine()) != null) {
System.out.println("Process -> " + read);
}
System.out.println("Finished executing.");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
while (scanner.hasNext()) {
String cmd = scanner.nextLine();
System.out.println(cmd + " -> Process");
printWriter.write(cmd + "n");
printWriter.flush();
}
scanner.close();
printWriter.close();
outputReader.close();
process.destroy();
}

最新更新