Windows cmd java command

Java Program to open the Command Prompt and Insert commands

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 the java code.

Читайте также:  Forum viewtopic php версии

These programs may not work in online programming environments. The details of how to run these programs by using javac and java commands are given in detail in this article, in the output section.

Algorithm

  • Step 1 − Using Java code open the CMD window.
  • 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 opened CMD window through the Java program.
  • Step 4 − See the result.

Multiple Approaches

For these programs, the choice of commands is done using two different approaches.

  • 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[] ); // the following line can also be used. //Runtime.getRuntime().exec(new String[] ); > 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>

Approach-1: By Using Commands that change the property of the cmd window.

In this approach, two different examples are used.

  • Example 1: Change the Title of the CMD window while opening it.
  • Example 2: Change the background and foreground color of the CMD window while opening it.
Читайте также:  Java reader readline while

Example 1: Change the Title of the CMD window while opening it.

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

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

Approach-2: By Using the executable commands

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

Example 1 Display the message in the opened CMD window.

Example 2 Show the contents of a txt file.

Example 3 Show the folder contents in a wide format.

Example 1: Display the message in the opened 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)

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

Example 2: Show the contents of a 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 .

Example 3: Show the folder contents in a 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 .

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.

Источник

How to Run a Java Program from the Command Prompt

Featured Image Run Java Program From Windows Command Prompt

Java is one of the most commonly used programming languages. It is also an IDE-intensive programming language, with tight integration with Eclipse. You can run Java programs from the Command Prompt for quick compiling and execution.

If you are just starting to learn Java, this basic guide will help you start running the Java application from the Command Prompt in Windows 10/11.

Content

Installing the Java Development Kit (JDK) in Windows

Before you can run a Java program on your computer, you’ll need to have a dedicated compiler installed. This comes within the Java Standard Edition Development Kit (JDK). It’s an essential tool for developing in Java on any platform.

The JDK is not the same as the Java Runtime Environment (JRE), which you’ll already have installed if you’ve ever used a Java application on your machine.

Java Windows Cmd Download Java Latest Version

  1. Download the JDK from Oracle’s website – the Windows version. Download any of the following: an x64 installer (shown in the screen), an x64 compressed archive, or an x64 MSI installer.

Note: if you have just simple use for Java software, make sure you do not download the “Java SE Development Kit for Java SE subscribers,” which is on the same download page. If you wish to use Java’s JRE installation for Microsoft Windows, it has been moved to another page.

Java Windows Cmd Download Java Latest Windows Installer

Java Windows Cmd Installer Installation Wizard Start

  1. Note the Windows location where Java is being installed. It will come in handy later when you’re trying to run Java from the Command Prompt.

Java Windows Cmd Java Location On Pc

  1. The installation should be over in just a few seconds. If it is taking a long time, close all of your other apps from Task Manager and reinstall the software.

Java Windows Cmd Installation In Progress

Java Windows Cmd Successful Installation Message

Running a Java Program From the Command Prompt

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }

Java Windows Cmd Java Program In Notepad

Java Windows Cmd Save Notepad File As Java Extension

Java Windows Cmd Open Command Prompt As Admin

  1. Use the cd command to change your working directory to the directory containing your Java program. To know which directory to go to, check the saved location of Java on your PC as discussed above.
cd Documents[Java-program-folder]
  1. From here, locate the path to the version of the Java Development Kit (JDK) on your computer. For example, if you’re running 64-bit Windows, that will often be in “C:\Program Files\Java.”

Java Windows Cmd Cd Change Directory To Java

set path=%path%;C:\Program Files\Java\jdk-"Java Version Number".bin
  1. You may need to change the directory path to reflect the current version of Java. Make sure you’re using the Java Development Kit (JDK) directory and pointing to the “bin” folder.

Java Windows Cmd Cd Change Directory To Jdk Bin

Note: the Java Runtime Environment (JRE) folder also contains a “bin” folder but doesn’t hold the Java compiler. If you get errors around the compilation, make sure you’re using the correct directory path.

  1. Compile the Java program with the javac command as shown below. Be warned that you won’t see anything happen. However, if you use the dir command, you’ll notice a new file in your directory ending in the “.class” extension, indicating the program has been compiled.

Java Windows Cmd Test Java Program Command Prompt

Java Windows Cmd Java Prog Running

You’ll see the program run within the Command Prompt window, but there’s one more task you can do to make sure your Java program runs smoothly: set your path.

Setting a Permanent PATH

The above command doesn’t set your Java compiler PATH permanently. It sets the environment variable for that session, but that change will be wiped away when you close the Command Prompt session.

Setting your Java compiler PATH permanently can come in handy if you want your compiled Java programs to run smoothly after a PC reboot. This helps launch the requested programs quickly from the Command Prompt window (or a third-party software like Eclipse).

Follow the steps below to change your PATH variable for all future sessions.

Java Windows Cmd Cd Control Panel System

Java Windows Cmd Select Advanced System Settings

  1. Click the “Environment Variables” button at the bottom after you’ve switched to the “Advanced” tab in the “System Properties” window.

Java Windows Cmd System Properties Advanced Environment Variables Select

Java Windows Cmd Environment Variables Path Edit 2

Java Windows Cmd Environment Variables New Path

  1. Paste the directory path you used above into the text box. Again, make sure you’re using the Java Development Kit (JDK) directory and not the Java Runtime Environment (JRE) directory next to it.

Java Windows Cmd Environment Variables Permanent Path

This article featured a simple Java program, but you can initiate almost any Java program from the Command Prompt. The procedure is straightforward regardless of the nature of your program.

Frequently Asked Questions

How can I fix «You don’t have permission to save in this location» while saving Java files?

Some users may get a “You don’t have permission to save in this location” error while saving Java files in Windows. Even though you are the administrator of your PC, this error shows up out of nowhere. To fix the problem, right-click the Java folder’s “Properties” and navigate to the “Security -> Advanced -> Select User or Group.”

In the “Advanced Security” settings for Java, change the “Owner” from “System” to whatever user account you have used to log in to the device. You can determine the correct name from “Check names.” Just enter the text, such as “Desktop,” “Administrator,” or “Users,” to enable full permissions to the folder. Click “OK” and save the changes.

How can I fix «Java is not recognized as an internal or external command» in Windows?

The best way to fix “Java is not recognized as an internal or external command” is to add Java’s bin directory to your computer’s path, as covered above.

Windows Command Prompt doesn’t show the results of Java command. How can I fix it?

If your Windows Command Prompt doesn’t show the results of a Java command you’ve entered, there are two solutions: run the Command Prompt in Administrator Mode or find your “Java.exe” file in the folder location and open its “Properties.” Then, navigate to the “Compatibility” tab where you will have to uncheck the “Run this program as an administrator” option.

What is the difference between Java and Javascript?

Don’t confuse Java with Javascript, as they are two different entities:

  • Java came before Javascript. It was founded by Sun Microsystems in 1991-1995. Javascript was founded later by Netscape, an old browser company. Basically, Javascript is a very lightweight version of Java and still commonly used in browsers.
  • Java is a compiled program, whereas Javascript is interpreted.
  • Java is a static typed program, whereas Javascript is dynamically typed.
  • Java uses classes, and Javascript uses prototypes.

Image credit: WrightStudio via AdobeStock. All screenshots by Sayak Boral.

Sayak Boral is a technology writer with over eleven years of experience working in different industries including semiconductors, IoT, enterprise IT, telecommunications OSS/BSS, and network security. He has been writing for MakeTechEasier on a wide range of technical topics including Windows, Android, Internet, Hardware Guides, Browsers, Software Tools, and Product Reviews.

Our latest tutorials delivered straight to your inbox

Источник

Оцените статью