Table of Contents
algorithm
Multiple methods
Java Code (to start the new CMD window)
Output
Method 1: By using the command to change the cmd window properties.
Example 1: Change title when opening CMD window.
Program
Example 2: Changes the background and foreground color of the CMD window while opening it.
Output (Approach 2: Example 1)
Approach-2: By Using the executable commands
Example 1: Display message in the open CMD window.
Example 2: Display the contents of txt file.
Example 3: Display folder contents in wide format.
Conclusion
Home Java javaTutorial Java program opens command prompt and inserts command

Java program opens command prompt and inserts command

Aug 19, 2023 pm 12:29 PM
command prompt java program insert 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);
      }
   }
}
Copy after login

Output

C:\java\javaprgstu>javac cmdprog1.java
C:\java\javaprgstu>java cmdprog1
Opening cmd window
C:\java\javaprgstu>
Copy after login
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);
      }
   }
}
Copy after login

Output

C:\java\javaprgstu>javac cmdprog22.java
C:\java\javaprgstu>java cmdprog22
Opening cmd window
The child process is Alive: true
Copy after login
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);
      }
   }
}
Copy after login

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
Copy after login
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);
   }
Copy after login

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
Copy after login
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);
      }
   }
}
Copy after login

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 ...
Copy after login
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);
      }
   }
}
Copy after login

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 ...
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run a JAR file on Windows 11 or 10 How to run a JAR file on Windows 11 or 10 May 12, 2023 pm 06:34 PM

Windows 11 is capable of running a large number of file types with or without external third-party applications. Not only does it allow you to perform numerous tasks from the comfort of your PC, but it also ensures that you can take advantage of your PC's raw capabilities. Today, we'll take a look at a complex file type—jar—and tell you how to open it on your Windows 11 or Windows 10 PC. What is a jar file? jar is an archive package format that may or may not contain an executable Java program. These archives can contain Java applications or source code, which can then be used to compile and run applications without having to write separate code for each application. You can use various methods

How to install CAB files on Windows 11 How to install CAB files on Windows 11 Apr 30, 2023 pm 10:10 PM

What is a CAB file? The extension of CAB file is .cab, which is the abbreviation of WindowsCabinet file. This is a compressed file typically used to compress software installation packages such as device drivers or update files. CAB files support lossless compression, which makes the format ideal for compressing files where it is critical that the files can be extracted accurately, such as drivers and other updates. How to Install a CAB File on Windows 11 Using Command Prompt There are multiple ways to install a CAB file on Windows 11. One of the methods is to use command prompt to extract and install the files. You can also use the newer Windows PowerShell

How to fix the problem in Valorant that requires a system restart before playing? How to fix the problem in Valorant that requires a system restart before playing? Apr 24, 2023 pm 11:58 PM

Cheating has always been a big problem in online FPS games, even if Valorant didn't exist. It can ruin the gaming experience and reduce player interest in the game. Valorant has tried to overcome this shortcoming since its early days with its own RiotVanguard protection system. You need to restart the system after installing the game once. This is completely normal and the Vanguard system will start automatically. However, if you restart your system and still see "Your game requires a system restart to play. Please restart your computer." Leave a message on the home page? Many users have encountered this problem, so don’t worry. Follow these fixes for a quick solution. Fix 1 – Don’t quit Pioneer after restarting your computer

How to fix application error 0xc0000906 on Windows PC How to fix application error 0xc0000906 on Windows PC Apr 18, 2023 pm 10:55 PM

Some users are encountering the error “Application Error 0xc0000906” while trying to run the application on their systems and they are unable to proceed. A single application or multiple applications on your system may encounter this error. This may be due to file corruption, caching issues, use of third-party antivirus software that may block software applications, etc. In this article, we have some solutions that can help users eliminate the error. Try executing the command to scan system files and disable antivirus software as described below. So let’s get started! Method 1: Run SFC and DISM Scan Step 1 – Open Command Prompt as Administrator. To do this, type cmd in the window search bar, then hold down the ctrl+shift keys and press enter

How to safely set high priority for apps in Windows 11? How to safely set high priority for apps in Windows 11? May 06, 2023 pm 06:28 PM

Windows does a great job of allocating system resources to the processes and programs that need it most by assigning priorities to them. Most applications you install will run perfectly fine at the default "normal" priority level. Sometimes, however, you may need to run a program, such as a game, at a higher level than the default normal level to improve its performance. But this comes at a cost, and it's a deal worth pondering. What happens when you set an app to high priority? Windows has a total of six priority levels for running different processes and programs - low, below normal, normal, above normal, high and real-time. Windows will rank and queue applications based on their priority. The higher the priority, the application

How to quickly resolve Windows activation error code 0xc004c020? How to quickly resolve Windows activation error code 0xc004c020? Apr 26, 2023 pm 03:19 PM

Many of our readers have reported the 0xC004C020 error when trying to connect their computers to their organization's servers. This error prevents activation of its Windows operating system. While errors can be frustrating, we'll guide you through error 0xC004C020 when trying to activate Windows on an organization-linked computer. What causes error 0xC004C020? If you are trying to activate Windows on an organization-linked computer and encounter error 0xC004C020, the possible causes may be as follows: Non-MAK keys – If a non-MAK key is used on an organization-linked computer, the organization’s policies will It is not allowed to be activated. Key access lost after formatting

How to fix srttrail.txt on Windows 11 How to fix srttrail.txt on Windows 11 Apr 18, 2023 am 10:43 AM

For Windows users, there is nothing more annoying than having to face a blue screen error, especially one that is accompanied by a system crash. srttrail.txt error is one of them. While not technically a BSOD, bugs in your auto-repair environment are still symptoms of deeper issues derailing Windows and require intervention. What is srttrail.txt error? The srttrail.txt text file mentioned in the message is just a log maintained by Windows for all instances when it fails to start properly, and it will continue to appear if Windows gets stuck on startup. This error message mainly occurs at system startup, but may also occur in Windo

3 Ways to Open System 32 Folder on Windows 11 or 10 3 Ways to Open System 32 Folder on Windows 11 or 10 May 04, 2023 pm 10:01 PM

What is the System32 folder? System32 is one of the main folders used by Windows. During Windows installation, all necessary files and folders that are critical for the proper functioning of Windows are copied to this folder. These include important system files, related executable files used by Windows utilities, dynamic link libraries (DLLs), and even some software files are copied to this folder. However, don't be fooled by the name System32. This is true for both 32-bit and 64-bit computers. In a 64-bit machine, the System32 folder hosts the 64-bit files, while the 32-bit files are located in

See all articles