开发者

Headache - Running a batch file from java

开发者 https://www.devze.com 2023-04-12 09:38 出处:网络
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.

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 pa开发者_开发百科th 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){

    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号