Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 919
user989244 Avatar asked Dec 18 '25 10:12

user989244


2 Answers

(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/

like image 63
TacticalCoder Avatar answered Dec 20 '25 01:12

TacticalCoder


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){

    }
like image 21
Dan Murray Avatar answered Dec 20 '25 02:12

Dan Murray



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!