简体   繁体   中英

Headache - Running a batch file from java

So let me start by saying I've gone though every Q&A I can find, both on/off the site, and I'm still hitting a brick wall.

My Program:

All my program does is run a batch file in the same directory as my program.

The code is:

try {

        Process p = Runtime.getRuntime().exec("cmd /c start startclient.bat");

      } catch (IOException ex) {

        Logger.getLogger(MCPFrame.class.getName()).log(Level.SEVERE, null, ex);

      }
    }

When I execute the code I get the warning window:

Windows cannot find 'startclient.bat'. Make sure you typed the name correctly, and then try again.

If I specify the directory with:

Process p = Runtime.getRuntime().exec("cmd /c start C:\\Folder\\startclient.bat");

I get:

The system cannot find the path specified.
Press any key to continue . . . 
C:\Windows\system32>

So my uneducated guess is that when I'm calling the batch file through java it's starting in "C:\\Windows\\system32>" but when I just double click the batch file its starting from the local directory.

How do I fix this?

:(

PS The kicker is, I actually had this thing working last year but for some reason it won't behave anymore.

PPS I'm running Win 7 and everything is up to date.

(I'd simply comment but I don't have enough rep yet to comment hence this "answer")

I've worked with a lot of batch files called from Java (both on Linux, OS X and Windows) and the first thing to know is that you should basically never ever use the constructor taking a string because it is, well, just problematic.

You're better to always create the array of arguments yourself and use this method:

public Process exec(String [] cmdArray)

You also have to know that correctly consuming the streams can be tricky. In many cases you're better to simply use libraries that make working with batch files easier.

For example, instead of re-inventing the wheel you may like Apache's commons exec here:

http://commons.apache.org/exec/

When i specify the directory like C:\\Folder\\startclient.bat I have the back slashes after

C:\\ as forward slashes and only one.

C:\\Folder/startclient.bat

Below should work for you. Well, i hope so. works for me.

    try {
        Runtime rt = Runtime.getRuntime();
        rt.exec("cmd.exe /c start C:\\Folder/startclient.bat");
    } catch (Exception ex){

    }

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