Executing an external program with path variable s

2019-05-06 17:11发布

I'm looking to execute an external program through the command line, but I've found I'm only able to do so if the program exists in the directory I am calling it from. I would like to be able to execute the program from any directory.

I've set the Path variable for windows (7) and am able to execute the program from any directory manually with the command line; however i am unable to do so through Java.

Relevant code:

 Runtime rt = Runtime.getRuntime();

 Process proc = rt.exec(new String[]{"C:\\AutomateKPI\\GetLog.exe", "-e", rossIP});

My issue is that the output of the above program produces a generically named file "log.txt". This will cause problems when threading my program. If it is impossible to use the path variable, alternatively i can copy the program into the new directory and delete it afterwards. I would like to avoid doing so.

Edit: The above code works as GetLog.exe resides in C:\AutomateKPI. I would like to reference %PATH% so I can run GetLog.exe from C:\AutomateKPI\*NewDir*

2条回答
放我归山
2楼-- · 2019-05-06 17:11

Well, as long as you know the path of the program that you're opening, and you dont have to use cmd, this should work every time:

File file = new File("File Directory");
Desktop dt = Desktop.getDesktop();

try {
    dt.open(file);
} catch (IOException e1) {
}
查看更多
\"骚年 ilove
3楼-- · 2019-05-06 17:25

Try using ProcessBuilder. It allows you to specify the working directory:

String commandPath = "C:" + File.pathSeparator +
                     AutomateKPI" + File.pathSeparator + "GetLog.exe";
ProcessBuilder pb = new ProcessBuilder(commandPath, "-e", rossIP);
pb.directory(new File("intendedWorkingDirectory"));
Process p = pb.start();

Or, if C:\AutomateKPI is in your %PATH%:

ProcessBuilder pb = new ProcessBuilder("GetLog.exe", "-e", rossIP);

It's unclear from the docs, but ProcessBuilder appears to locate things in a way that's similar to the system, e.g. using %PATH% on windows.

查看更多
登录 后发表回答