Executing an external program with path variable set in Java?

女生的网名这么多〃 提交于 2019-12-07 08:28:58

问题


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*


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/11885326/executing-an-external-program-with-path-variable-set-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!