View RSS Feed

My Java Tips

Execute An External Program From Java

Rate this Entry
by , 11-08-2011 at 06:49 PM (1142 Views)
A Java programmer may need to access the environment under which the application is running. It is supported by getRuntime method in Runtime Class. Programmer need not create an instance of Runtime class, Instead the Java application has a single instance of class Runtime environment in which the application is running.

Runtime class has several methods that are useful to execute an external program, getting Information about processors, Memory Information etc.

Following program executes an external program JavaTipsEbook.exe which is located at Local Drive.



Java Code:
import java.io.*;

public class CommandExection {

 public CommandExection(String commandline) {

 	try {

 		String line;

 		Process p = Runtime.getRuntime().exec(commandline);

 		BufferedReader input =

 			new BufferedReader

 			(new InputStreamReader(p.getInputStream()));

 		while ((line = input.readLine()) != null) {

 			System.out.println(line);

 		}

 		input.close();

 	}

 	catch (Exception err) {

 		err.printStackTrace();

 	}

 }	public static void main(String argv[]) {

 	new CommandExection("c:JavaTipsEbook.exe");

 }

}
Code Explanation: Here exec method of Runtime class is used, Which takes a string as an argument and instructs underlying environment to run the command. User can run any command like mkdir , cmd etc. It returns an object of Process Class which is processed using BufferedReader to show the result returned by underlying run time environment .

Runtime Class has several other methods as well. Description of some important methods are as below.

public void exit(int status): Terminates the currently running Java Virtual Machine by initiating its shutdown sequence.

public void halt(int status): Forcibly terminates the currently running Java Virtual Machine. This method never returns normally.

public int availableProcessors(): Returns the number of processors available to the Java Virtual Machine.

public long freeMemory(): Returns the amount of free memory in the Java Virtual Machine.

public long totalMemory(): Returns the total amount of memory in the Java Virtual Machine.

public long maxMemory(): Returns the maximum amount of memory that the Java Virtual Machine will attempt to use.

There are a lot of other useful methods too. For that refer Java API For Runtime Class.

Submit "Execute An External Program From Java" to Facebook Submit "Execute An External Program From Java" to Digg Submit "Execute An External Program From Java" to del.icio.us Submit "Execute An External Program From Java" to StumbleUpon Submit "Execute An External Program From Java" to Google

Categories
Java SE

Comments