search
HomeJavajavaTutorialJava program opens command prompt and inserts command

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 via Java code.

These programs may not run in online programming environments. Details on how to run these programs using javac and java commands are detailed in the output section of this article.

algorithm

  • Step 1 − Open the CMD window using Java code.

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

  • Step 3 - Execute the selected command in the open CMD window through the Java program.

  • Step 4 − Check the results.

Multiple methods

For these programs, command selection is accomplished through two different methods.

  • 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);
      }
   }
}

Output

C:\java\javaprgstu>javac cmdprog1.java
C:\java\javaprgstu>java cmdprog1
Opening cmd window
C:\java\javaprgstu>
Java program opens command prompt and inserts command

Method 1: By using the command to change the cmd window properties.

In this approach, two different examples are used.

  • Example 1: Change title when opening CMD window.

  • Example 2: Change the background and foreground colors when opening the CMD window.

Example 1: Change title when opening CMD window.

Program

public class cmdprog22 {
   public static void main(String[] args) {
      String command_to_playwith =" title 'The New Title of the New Command Window' ";
      System.out.println("Opening cmd window");
      try {
         String command = "cmd /c" + " start" + command_to_playwith;
         //Starting the new child process
         Process childprocess11 = Runtime.getRuntime().exec(command);
         System.out.println("The child process is Alive: " + childprocess11.isAlive());
         System.out.println();
      }
      catch (Exception e){
         System.out.println("Error: " + e);
      }
   }
}

Output

C:\java\javaprgstu>javac cmdprog22.java
C:\java\javaprgstu>java cmdprog22
Opening cmd window
The child process is Alive: true
Java program opens command prompt and inserts command

Example 2: Changes the background and foreground color of the CMD window while opening it.

public class cmdprog55 {
   public static void main(String[] args) {
      
      //the following command will change the color of the cmd window. First the number for bg color and then the number for fg color is added.
      // 4 means red color and 0 means black color
      String command_to_playwith =" COLOR 40";
      System.out.println("Opening cmd window");
      try {
         String command = "cmd /c" + " start" + command_to_playwith;
         
         // starting the child process ....
         Process childprocess11 = Runtime.getRuntime().exec(command);
         System.out.println("The child process is Alive: " + childprocess11.isAlive());
         System.out.println();
      }
      catch (Exception e){
         System.out.println("Error: " + e);
      }
   }
}

Output (Approach 1: Example 2)

C:\java\javaprgstu>javac cmdprog55.java
C:\java\javaprgstu>java cmdprog55
Opening cmd window
The child process is Alive: true
Java program opens command prompt and inserts command

Approach-2: By Using the executable commands

A new cmd window is opened as a child process. The inserted command results can only be seen in a new cmd window. In this approach, three different examples are used.

Example 1: Display message in the open CMD window.

Example 2 Show the contents of a txt file.

Example 3: Display folder contents in wide format.

Example 1: Display message in the open CMD window.

public class cmdprog44 {
   public static void main(String[] args) {
      
      // The following command will display the message specified.
      String command_to_playwith =" ECHO 'Hi! Lets check the cmd commands ....'";
      System.out.println("Opening cmd window");
      try {
         String command = "cmd /c" + " start" + command_to_playwith;
         // starting the child process....
         Process childprocess11 = Runtime.getRuntime().exec(command);
         System.out.println("The child process is Alive: " + childprocess11.isAlive());
         System.out.println();
      }
      catch (Exception e){
         System.out.println("Error: " + e);
      }
   }
}
System.out.println("Opening cmd window");
   try {
      String command = "cmd /c" + " start" + command_to_playwith;
      // starting the child process ....
      Process childprocess11 = Runtime.getRuntime().exec(command);
      System.out.println("The child process is Alive: " + childprocess11.isAlive());
      System.out.println();
   }
   catch (Exception e){
      System.out.println("Error: " + e);
   }

Output (Approach 2: Example 1)

C:\java\javaprgstu>javac cmdprog44.java
C:\java\javaprgstu>java cmdprog44
Opening cmd window
The child process is Alive: true
Java program opens command prompt and inserts command

Example 2: Display the contents of txt file.

public class cmdprog33 {
   public static void main(String[] args) {
      
      //The following command is the command that is needed to see the contents of the given text file
      String command_to_playwith =" TYPE testfile.txt";
      System.out.println("Opening cmd window");
      try {
         String command = "cmd /c" + " start" + command_to_playwith;
         
         //Starting the new child process
         Process childprocess11 = Runtime.getRuntime().exec(command);
         System.out.println("The child process is Alive: " + childprocess11.isAlive());
         System.out.println(" Now showing the content of testfile.txt ....\n");
      }
      catch (Exception e){
         System.out.println("Error: " + e);
      }
   }
}

Output

C:\java\javaprgstu>javac cmdprog33.java
C:\java\javaprgstu>java cmdprog33
Opening cmd window
The child process is Alive: true
Now showing the content of testfile.txt ...
Java program opens command prompt and inserts command

Example 3: Display folder contents in wide format.

public class cmdprog66 {
   public static void main(String[] args) {
      
      // The following command will display the specified directory in wide format
      String command_to_playwith =" dir .\applettest /W";
      System.out.println("Opening cmd window");
      try {
         String command = "cmd /c" + " start" + command_to_playwith;
         
         //Starting the new child process
         Process childprocess11 = Runtime.getRuntime().exec(command);
         System.out.println("The child process is Alive: " + childprocess11.isAlive());
         System.out.println(" Now showing the directory in wide format ....\n");
      }
      catch (Exception e){
         System.out.println("Error: " + e);
      }
   }
}

Output

C:\java\javaprgstu>javac cmdprog66.java
C:\java\javaprgstu>java cmdprog66
Opening cmd window
The child process is Alive: true
Now showing the directory in wide format ...
Java program opens command prompt and inserts command

Conclusion

In this article, we explored different commands to be inserted into the cmd window after opening it through the java program. The selection of commands is done based on the different categories. The first set of commands changes the properties of the command window while opening it and the second set of commands is used to show results in the opened command window after it is displayed. In both cases, the new cmd window is opened as a child process.

The above is the detailed content of Java program opens command prompt and inserts command. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!