How to run native commands in Java

December 2, 2007 – 11:52 am

[I am referring to Windows]

Step 1

  1. Right Click ‘My Computer’ & Select Properties
  2. Go To ‘Advanced’ & Select ‘Environment Variables’
  3. Go To ‘System Variables’ and add the path to your command in ‘Path’

Step 2

  1. Make a batch file with necessary commands [Say ‘time 12:00′]
  2. Save it as c:\\test.bat

Step 3 : Lets dirty our hand with Java


try{
Runtime rt = Runtime.getRuntime() ;

       // batch file is in C:\ 

String command = cmd /c c:\\test.bat;
System.out.println( command: + command);

       // executes batch file

Process p = rt.exec(command) ;

       // outputs int

System.out.println(”output: ” + p.getInputStream().read());

       // necessary for waiting for the process to execute the commands

p.waitFor();
p.destroy() ;
}catch(Exception exc){

       //handle exception

}

Post a Comment