I need to execute a .exe file from a function in one of the packages I have in my java project. now the working directory is the root directory of the project for java but t
I goted a same problem in my project, I tryed this solutions about ProcessBuilder.directory(myDir)
and the exec method from Runtime
and all my trays failed..
It's make me understanding that the Runtime
have a limited privileges just for the working directory and the sub directories of it.
So my solution is ugly but working very well.
I create a temporary .bat file in "runtime" in the working directory.
This file included two lines of commands:
1. Move to needed directory (cd command).
2. Do the command in need.
I call the exec from Runtime
with my temporarily .bat file as command.
It's work for me very well!
Use this form of the exec method to specify a working directory
public Process exec(String[] cmdarray,
String[] envp,
File dir)
throws IOException
The working directory is the third argument. You can pass null
for envp
if you don't need to set any special environment.
There's also this convenience method:
public Process exec(String command,
String[] envp,
File dir)
throws IOException
...where you specify the command in one string (it just gets turned into an array for you; see the docs for details).
To implement this you can use the ProcessBuilder class, here's how it would look like:
File pathToExecutable = new File( "resources/external.exe" );
ProcessBuilder builder = new ProcessBuilder( pathToExecutable.getAbsolutePath(), "-i", "input", "-o", "output");
builder.directory( new File( "resources" ).getAbsoluteFile() ); // this is where you set the root folder for the executable to run with
builder.redirectErrorStream(true);
Process process = builder.start();
Scanner s = new Scanner(process.getInputStream());
StringBuilder text = new StringBuilder();
while (s.hasNextLine()) {
text.append(s.nextLine());
text.append("\n");
}
s.close();
int result = process.waitFor();
System.out.printf( "Process exited with result %d and output %s%n", result, text );
It's quite a bunch of code, but gives you even more control on how the process is going to be run.