问题描述
我正在寻找通过命令行执行外部程序的方法,但是我发现只有当程序存在于我从中调用它的目录中时,我才能这样做.我希望能够从任何目录执行程序.
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.
我已经为Windows(7)设置了Path变量,并且能够使用命令行从任何目录手动执行该程序;但是我无法通过Java做到这一点.
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.
相关代码:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(new String[]{"C:\\AutomateKPI\\GetLog.exe", "-e", rossIP});
我的问题是上述程序的输出产生了一个通用名称的文件"log.txt".这将在线程我的程序时引起问题.如果无法使用path变量,或者可以将程序复制到新目录中,然后再将其删除.我想避免这样做.
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.
上面的代码作为GetLog.exe驻留在C:\ AutomateKPI中工作.我想引用%PATH%,以便可以从C:\ AutomateKPI \ * NewDir *
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*
推荐答案
尝试使用 ProcessBuilder
.它允许您指定工作目录:
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();
或者,如果 C:\ AutomateKPI 在您的%PATH%
中:
ProcessBuilder pb = new ProcessBuilder("GetLog.exe", "-e", rossIP);
从文档中尚不清楚,但ProcessBuilder
似乎以类似于系统的方式来定位事物,例如在Windows上使用%PATH%
.
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.
这篇关于执行带有Java中设置的路径变量的外部程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!