Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a bat from from a java program

I have created a bat file to call a java class. Now I have created a GUI in swing. In that swing I have a button as start and for that I have action Listener in which I created the following code

public void actionPerformed(java.awt.event.ActionEvent evt)
{
    try 
    {

        File file = new File("F:/myprog/start.bat");

        Desktop.getDesktop().open(file);

    } catch (IOException e)

    {

        e.printStackTrace();

    }

    jButton1ActionPerformed(evt);

}

When I run click the button I get "Error: Could not find or load main class"

Batch file :

javac *.java
java websphinx.workbench.Workbench
 pause

When I click the bat file the application is running. But from Java program when I call this bat file I get the error. What went wrong?

like image 346
Murali Avatar asked Jan 19 '26 12:01

Murali


1 Answers

In Java one usually runs a command while Runtime.getRuntime().exec, you'll need to pass cmd.exe as the file to run, and then the batch name as a parameter.

try {
     Process p = Runtime.getRuntime().exec(
                    new String[]{"cmd.exe", "/c", "F:/myprog/start.bat"});
     InputStream in = p.getInputStream();
     OutputStream out = p.outputStream();
} catch (IOException e){
     e.printStackTrace();
}
like image 85
Dr BDO Adams Avatar answered Jan 21 '26 01:01

Dr BDO Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!