Command method in java

How to Execute Operating System Commands in Java

This Java File IO tutorial guides you how to write Java code to run native commands of the host operating system.

Although Java is a cross-platform programming language, sometimes we need to access to something in an operating system dependent way. In other words, we need a Java program to call native commands that are specific to a platform (Windows, Mac or Linux). For example, querying hardware information such as processer ID or hard disk ID requires invoking a kind of native command provided by the operating system. Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.

Basically, to execute a system command, pass the command string to the exec() method of the Runtime class. The exec() method returns a Process object that abstracts a separate process executing the command. From the Process object we can get outputs from and send inputs to the command. The following code snippet explains the principle:

String command = "command of the operating system"; Process process = Runtime.getRuntime().exec(command); // deal with OutputStream to send inputs process.getOutputStream(); // deal with InputStream to get ordinary outputs process.getInputStream(); // deal with ErrorStream to get error outputs process.getErrorStream();

The following code snippet runs the ping command on Windows and captures its output:

Читайте также:  Php примеры логические операторы

String command = «ping www.codejava.net»; try < Process process = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); > catch (IOException e)

Pinging codejava.net [198.57.151.22] with 32 bytes of data: Reply from 198.57.151.22: bytes=32 time=227ms TTL=51 Reply from 198.57.151.22: bytes=32 time=221ms TTL=51 Reply from 198.57.151.22: bytes=32 time=220ms TTL=51 Reply from 198.57.151.22: bytes=32 time=217ms TTL=51 Ping statistics for 198.57.151.22: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 217ms, Maximum = 227ms, Average = 221ms

1. Getting Standard Output

For system commands that produce some output as result, we need to capture the output by creating a BufferedReader that wraps the InputStream returned from the Process :

BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream()));

Then invoke the readLine() method of the reader to read the output line by line, sequentially:

String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close();
Scanner scanner = new Scanner(process.getInputStream()); scanner.useDelimiter("\r\n"); while (scanner.hasNext()) < System.out.println(scanner.next()); >scanner.close();

2. Getting Error Output

A command is not always executed successfully, because there would be a case in which the command encounters an error. And typically, error messages are sent to the error stream. The following code snippet captures the error input stream returned by the Process :

BufferedReader errorReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); while ((line = errorReader.readLine()) != null) < System.out.println(line); >errorReader.close();

So it’s recommended to capture both the standard output and error output to handle both normal and abnormal cases.

3. Sending Input

For interactive system commands which need inputs, we can feed the inputs for the command by obtaining the OutputStream returned by the Process . For example, the following code snippet attempts to change system date on Windows to 09-20-14 (in mm-dd-yy format):

String command = «cmd /c date»; try < Process process = Runtime.getRuntime().exec(command); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(process.getOutputStream())); writer.write("09-20-14"); writer.close(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); > catch (IOException e)

The current date is: Sat 09/20/2014 Enter the new date: (mm-dd-yy) 09-20-14

4. Waiting for the process to terminate

For long-running command (e.g. batch script), we can make the calling thread to wait until the process has terminated, by invoking the waitFor() method on the Process object. For example:

int exitValue = process.waitFor(); if (exitValue != 0)

Note that the waitFor() method returns an integer value indicating whether the process terminates normally (value 0) or not. So it’s necessary to check this value.

5. Destroying the process and checking exit value

It’s recommend to destroy the process and checking its exit value to make sure the system command’s process is executed successfully and exited normally. For example:

process.destroy(); if (process.exitValue() != 0)

NOTE: Using the waitFor() and exitValue() method is exclusive, meaning that either one is used, not both.

6. Other exec() methods

Beside the primarily used method exec(String command) , the Runtime class also has several overloaded ones. Notably this one:

exec(String[] cmdarray)

This method is useful to execute a command with several arguments, especially arguments contain spaces. For example, the following statements execute a Windows command to list content of the Program Files directory:

String commandArray[] = ; Process process = Runtime.getRuntime().exec(commandArray);

API References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Command Pattern with Java examples

command pattern class diagram

This pattern falls under the behavioral design pattern category. In this pattern, the information inside one request is mapped to a single object and then that object is used as required. It encapsulates a whole request as an object called ‘Command’. The ‘Command’ can be identified as a materialized method call. That object often contains a batch of queued commands with rollback capabilities. Service requester, who initiates the request is not aware how the job will be completed or which requests are sent to the appropriate parties.

‘Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo of operations’

The definition highlights the importance of the pattern in several aspects. The command pattern will serve not only for a single request for one-time use. It is a way of executing a set of requests or a series of commands as well as rolling back a series of commands.

What is ‘Command’ Object?

This is the intermediary object that links the request invoker, which triggers the request and the request receiver, which handle the request by performing several operations. It does not execute any functionality but contains all the information required to perform an operation. The information can be an object, a method to apply to an object and method arguments if required. Command object will contain only one method called ‘execute()’ and it will trigger the actual operations from request receiving end. In addition, this command object act as the main interface for all the internal commands and a sequence of command objects can be assembled into a composite command. This materialization of commands as objects enable the requests to perform passing, staging, sharing and treating as table entries.

Structure of the Command Pattern: Class Diagram

command pattern class diagram

Components of the Command Pattern

This is the main entry point to execute a complex set of commands. Client calls the invoker’s execute command method to access the command interface. Invoker stores a reference of a command object to trigger the operation executed when required. It is unaware of the concrete command and does not create any command objects, but instruct the available command object to carry out the request.

This object knows how to perform the actual operations and carry out the actions to fulfil the request. That means it contains the business logic or data related to response creation.

The client instantiates a concrete command object and passes those to appropriate invokers. It creates the invoker and receiver objects as well. Then it checks and decides which receiver objects link with the command objects and which commands to link with the invoker. In addition, it decides which command to execute at which points

How Does the Command Pattern Works?

The client needs to fulfil a request from an external party. The external party is identified as the receiver, but the client doesn’t know how the receiver performs the operation. The client contains the required objects to perform the request. The command is the high-level representation of the concrete command implementation. That is several concrete commands can be inside one scenario.

First, the client creates a ‘Receiver’ object and then attach it to the command object. The command object is responsible to pass the request to the appropriate ‘Receiver’ method, which caters for the request. Then, the client creates the invoker object and attach the command object to route the appropriate action. The Invoker holds a command and can get the Command to execute a request by calling the execute method. The Receiver has the knowledge of what to do to carry out the request.

Command Pattern Example

Let’s assume a smart home electrical unit system that controls by a universal remote. There are two kinds of systems, which are operated by the universal remote. Those two are the living room light system and Air Conditioner. We will include those two sub-systems into a super system as ‘Home Electronics’. Universal remote has two buttons as ‘On’ and ‘Off’. When the homeowner press ‘On’ both the light system and air-conditioned activates.

  • Command: Command interface to initiate the execution and abstract the concrete commands.
  • OnCommand: Concrete command class that implements the ‘On’ operations for the ‘HomeElectronics’
  • OffCommand: Concrete command class that implements the ‘Off’ operations for the ‘HomeElectronics’
  • UniversalRemote: UniversalRemote class will maintain all the receivers and will provide a method to identify the currently active receiver
  • HomeElectronics: Parent class for ‘LightSystem’ and ‘Airconditioner’ home electronic systems
  • LightSystemReceiver: Act as a ‘Receiver’ object for the scenario, contains actual method implementations to execute the required functions
  • AirconditionReceiver: Act as the ‘Receiver’ object for the scenario, contains actual method implementations to execute the required functions
  • ButtonInvoker: This class act as the invoker for any action
  • HomeOwnerClient: The client who needs the service of receivers

How to Implement the Pattern in Example

  1. Define the base interface ‘Command’ with the ‘execute()’ similar method
  2. Create concrete classes implementing the ‘Command’ interface and including a ‘Receiver’ object instance with appropriate arguments to perform the concrete execution
  3. Include an instance of ‘Command’ inside the ‘Invoker’ object
  4. The client creates the ‘Command’ and ‘Invoker’ instances and passes a command instance to the invoker instance
  5. Then invoker decides and triggers the ‘execute()’ method at the required time
  6. Finally, receivers get the signal and execute the actual methods to cater the request

High-Level Diagram

command pattern example

Code Samples

Command.java

Источник

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