简体   繁体   中英

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?

A batch file in intself is not an executable and is normaly run within its interpreter, thus you will need to start it with the cmd.exe

Try the following

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "F:\\myprog\\start.bat");
Process p = pb.start();

An alternative to this is:

Runtime.getRuntime().exec("cmd /c start F:/myprog/start.bat");

The Processbuilder is the preferred alternative, though. It gives you much more control over the external process, as you can instruct your program to wait for the batch file to complete its execution or run concurrent to it.

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();
}

试试这个

Runtime.getRuntime().exec("cmd /c start F:/myprog/start.bat");

i THINK its not a batch file issue,

looking at Error: Could not find or load main class

it looks like a classpath issue

you might need to improve your batch file

javac *.java
java -cp yourdrive:\path\to\class websphinx.workbench.Workbench
 pause

see the -cp variable.

The thing that when you execute batch file as is it runs and when from your program it gives exception , could be because of change of scope. your java class and your batch file may not be at same location to say.

You use the Runtime#exec method for this:

Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", "F:\\myprog\\start.bat" });

Note that the program you're really running is cmd.exe , with the /c switch, followed by the batch filename with the path in Windows format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM