Java程序打开命令提示符并插入命令

This article uses various approaches for selecting the commands inserted in the opened command window through the Java code. The command window is opened by using ‘cmd’. Here, the methods of doing the same are specified using Java code. The Command window is first opened using the Java program. It is opened as a child process. If the java program is run in an existing cmd window, another one is opened as a new process. Further, different types of commands are inserted and executed in that opened command window 通过Java代码。

这些程序可能在在线编程环境中无法运行。如何使用javac和java命令运行这些程序的详细信息在本文中的输出部分中详细说明。

算法

  • 步骤 1 − 使用 Java 代码打开 CMD 窗口。

  • Step 2 − Select the command to be executed. The selected command is used as a text String.

  • 第三步 - 通过Java程序在打开的CMD窗口中执行所选命令。

  • 第四步 − 查看结果。

多种方法

对于这些程序,命令的选择是通过两种不同的方法来完成的。

  • By Using Commands that change the property of the cmd window.

  • By Using Executable Commands

Let’s see the program along with its output one by one.

First, the java code is given to start the new CMD window.

Java Code (to start the new CMD window)

public class cmdprog1 { public static void main(String[] args) { System.out.println("Opening cmd window"); try{ // cmd is a command that opens the command window //CMD /C is used to run commands and then terminate the existing window while CMD /K will run the command and then it returns you to the given prompt. Runtime.getRuntime().exec(new String[] {"cmd", "/K", "Start"}); // the following line can also be used..... //Runtime.getRuntime().exec(new String[] {"cmd", "/C", "Start"}); } catch (Exception e){ System.out.println("Error: " + e); } } } 登录后复制