How to Execute Console Commands in Java

An old engineering saying declares that you should never "reinvent the wheel," and this applies to programming as well. If a console application already does the work you need, rather than rewrite and redebug the code to make it happen, Java allows you to execute that console command and read the results. The keys are the Runtime and Process classes in the Java standard library.

Instructions

    • 1

      Open Netbeans or your favorite Java Integrated Development Environment.

    • 2

      Click "File" and "New" to create a new class. Name the class "ConsoleTest."

    • 3

      Add the line: "import java.lang.*" to the top of the class.

    • 4

      Type "psvm" within the class. This will be expanded by Netbeans into a valid main method.

    • 5

      Type the following within the brackets of the "main" method:

      String cmd = "ping www.google.com";

      Process proc = Runtime.getRuntime().exec(cmd);

      This retrieves the current Runtime interface to the operating system and spawns a new process that runs the given command. Any valid console command can be used. This example "pings" the Google search engine to see how quickly it responds.

Tips & Warnings

  • The "Process" class provides about half a dozen methods for interacting with your newly spawned program. You can read the documentation for this class in the second reference.

  • Java is designed from the ground up to be a cross-platform language. However, console commands differ radically from one operating system to another and even from one version to another. You should ensure that your program runs the proper commands for the current operating system.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured