2

On clicking a button in a jsp page, I want to run a batch file. I wrote this code to execute a batch file inside a method, but it's not working. Plz help me out.

public String scheduler() {
    String result=SUCCESS;  
    try {

        Process p =  Runtime.getRuntime().exec("cmd /c start.bat", null, new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start"));

        System.out.println("manual scheduler for application.."+p);
    } catch(Exception e) {  
    }
}
Pieter
  • 895
  • 11
  • 22
Surya Rawat
  • 101
  • 3
  • 13

3 Answers3

1

Add this code,

batFile.setExecutable(true);

//Running bat file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_BAT_SCRIPT_FILE+File.separator+batFile.getName());                                                              
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);                              
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
    System.out.println("BAT script executed properly");
}
Aditya
  • 1,334
  • 1
  • 12
  • 23
0

According to this, the following code should work (just remove the cmd /c):

public String scheduler() {
    String result=SUCCESS;  
    try {

        File f = new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start")
        Process p =  Runtime.getRuntime().exec("start.bat", null, f);

        System.out.println("manual scheduler for application.."+p);
    } catch(Exception e) {   
    }
}
Community
  • 1
  • 1
mvieghofer
  • 2,846
  • 4
  • 22
  • 51
  • hi mvieghofer thanx for replying..but this sol is not working. Runtime.getRuntime().exec("cmd /c start scheduler1.bat") is working.but cmd by default taking path where weblogic batch file is stored.the path address i m giving through code is not working. – Surya Rawat Dec 20 '13 at 10:12
  • cmd taking default address E:\bea\user_projects\domain\base_domain.which is startWeblogic batch file address.i think app is running on server thats why its taking server batch file default address...confused. – Surya Rawat Dec 20 '13 at 10:22
0

It's not clear here whether you just want to run a bat file or you want to wait for it to run.

// the location where bat file is located is required eg. K:/MyPath/MyBat.bat in my case // If bat file is in classpath then you can provide direct bat file name MyBat.bat

 **Runtime rt = Runtime.getRuntime() ;
 Process batRunningProcess= rt.exec("cmd /c   K:/MyPath/MyBat.bat");**

// This is to wait for process to complete //if process is completed then value will be 0

 **final int exitVal =  lawTab_Indexer.waitFor();**

// This line is not required if you just want to run a bat file and dont want to wait for it to get completed.

  • i want to run a batch file from struts 2 application,onclicking a submit option.onclicking submit i m calling a method,which is given above.but function is not working. – Surya Rawat Dec 20 '13 at 10:15