changing the working-directory of command from java

user804723 picture user804723 · Jul 25, 2011 · Viewed 31.1k times · Source

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 the .exe file in sub-directories of my project. here is how the project is organized:

ROOT_DIR
|.......->com
|         |......->somepackage
|                 |.........->callerClass.java
|
|.......->resource
         |........->external.exe

Initially I tried to run the .exe file directly through:

String command = "resources\\external.exe  -i input -o putpot";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);

but the problem is external .exe needs to access some files in it's own directory and keeps thinking root directory is its directory. I even tried to use .bat file to solve the problem but the same issue rises:

Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "resources\\helper.bat"});

and the .bat file is in the same directory as the .exe file but the same issue happens. here is the content of the .bat file:

@echo off
echo starting process...

external.exe -i input -o output

pause

even if I move .bat file to root and fix its content the problem does not go away. plz plz plz help

Answer

Maurício Linhares picture Maurício Linhares · Jul 25, 2011

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.