Thursday, March 25, 2010

Execute a command from Java Program on Windows Mac or *nix System

I was working on some project and I wanted to write a code which will execute command from Java Program and it should run irrespective of Operating system.

So wrote a code and thought it will be nice to share, or may be it will be good for me, if I want to look at it after a while :)

The code below will run command from Java file even if it is Windows or Mac OS or Unix





//Package name is of the package
package finalgui;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
*
* @author Vinit Patwa
*/
public class RunCommand {

private static String ls_str;

public static void main(String args[]) {

try {
Process ls_proc;

//we want to run command "mvn clean install"
//It is expected that "mvn" is in your PATH
String mvnClean = "mvn clean install";

//We are storing the OS on system in String OS
String OS = System.getProperty("os.name");
System.out.println("OS is: " + OS);


if (OS.contains("Windows")) {
ls_proc = Runtime.getRuntime().exec("cmd.exe /C mvn clean install");
} else {
ls_proc = Runtime.getRuntime().exec(mvnClean);
}


//We can also display the output of the command Here
DataInputStream ls_in = new DataInputStream(
ls_proc.getInputStream());
try {
BufferedReader br = new BufferedReader(new InputStreamReader(ls_in));
while ((ls_str = br.readLine()) != null) {
System.out.println(ls_str);
}
} catch (IOException e1) {
System.exit(0);
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();

}
}
}

1 comment:

Identity Theft said...

If you want to run the command from some particular folder say '/users/bin/' then update the following section of above program as shown below:


if (OS.contains("Windows")) {
ls_proc = Runtime.getRuntime().exec("cmd.exe /C mvn clean install /users/bin/");
} else {
ls_proc = Runtime.getRuntime().exec(mvn clean install /users/bin/);
}