Running an external program with a path variable set in Java?

I want to execute an external program through the command line, but I found that I can only do this if the program exists in the directory with which I call it. I would like to be able to execute a program from any directory.

I set the Path variable for windows (7) and can execute the program from any directory manually using the command line; however, I cannot do this through Java.

Relevant Code:

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

My problem is that the output of the above program creates a file called "log.txt" with a common name. This will cause problems when flashing my program. If it is not possible to use the path variable, I can also copy the program to a new directory and delete it later. I would like to avoid this.

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

+4
source share
2 answers

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 is not clear from the documents, but ProcessBuilder seems to find things in a way that looks like a system, for example. using %PATH% in windows.

+5
source

Well, if you know the path to the program you are opening, and you do not need 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) { } 
0
source

All Articles