Saturday, July 16, 2016

Running batch file from Java

One of the most important requirement for batch file is to run the same command what we run from command line. If we type the series of command in normal file and save this file with .bat extension then this file converted to batch file. Above mentioned extension is only for windows machines for different operating machine batch extensions are different.

So now question is how to run a batch file from java ?

Sample snippet given below :

    public static void main(String[] args) throws IOException {
        try {
            String[] command = { "cmd.exe", "/C", "Start", "runTestNGScript.bat" };
            Process p = Runtime.getRuntime().exec(command);
        } catch (IOException ex) {
      }
    }


Sample batch file given below :
@echo off
echo Set JAVA Path

set PATH=%PATH%;G:\Program Files\Java\jdk1.7.0_79\bin

echo Now PATH is %PATH%


cd %cd%

echo Current Directory %cd%
echo Set Project Path
 
set ProjectPath=%cd%

echo Now project path is : %ProjectPath%


echo Set Class Path

set classpath=%ProjectPath%\bin;%ProjectPath%\lib\*

echo Now project Class path is : %classpath%

echo start compiling
 

javac test\com\automation\test\*.java -cp lib\* -d bin
 

echo Project compiled

echo run test class using TestNG
 

java org.testng.TestNG %ProjectPath%\testng.xml
 

echo Run completed
 

pause

No comments:

Post a Comment