2
try {                               
try {
    String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(command);
        p.waitFor();

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(this, "Error" +"Execution!","Error",JOptionPane.ERROR_MESSAGE);
        }
    } catch (IOException ex) {
        Logger.getLogger(DBBackUp.class.getName()).log(Level.SEVERE, null, ex);
    }

When I run this code, I got only command promt. .bat file is not running. How can I execute the batch file using this code?

Thank in Advance

  • Can you please share your test.bat and the command prompt response. Try to add echo message as first statement in your batch file to see if it is running. – Dinakar Mar 31 '13 at 15:04
  • If the bat file is a short running script then you may not be able to see the window. – Extreme Coders Mar 31 '13 at 15:06

3 Answers3

2

Consider using Apache Commons Exec.

noahlz
  • 10,202
  • 7
  • 56
  • 75
1

let your "test.bat" be like this:

dir
pause

then you can execute this batch file as follows:

try
{
 Runtime r = Runtime.getRuntime();
 Process p = r.exec("rundll32 url.dll,FileProtocolHandler " + "D:\\test.bat");
 p.waitFor();
}catch(Exception ex){ex.printStackTrace();}
Vishal K
  • 12,976
  • 2
  • 27
  • 38
1

You can try something like this:

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


public class BatchExecuteService {

    public static void main(String[] args) {
        BatchExecuteService batchExecuteService = new BatchExecuteService();
        batchExecuteService.run();
    }

    public void run() {
        try {
            String cmds[] = {"D:\\test.bat"};
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(cmds);
            process.getOutputStream().close();
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
            BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
            String strLine = "";
            while ((strLine = bufferedrReader.readLine()) != null) {
                System.out.println(strLine);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
1218985
  • 7,531
  • 2
  • 25
  • 31