Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing the working-directory of command from java

Tags:

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

like image 591
user804723 Avatar asked Jul 25 '11 03:07

user804723


People also ask

How do I change directory in Java terminal?

To change directories, use the cd command with the name of a directory. To return to the previous directory, use the cd command, but this time followed by a space and two periods. mkdir: To create a new directory, use the command mkdir.

How do you go to a directory in Java?

In Java, we can use System. getProperty("user. dir") to get the current working directory, the directory from where your program was launched.


1 Answers

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.

like image 110
Maurício Linhares Avatar answered Sep 19 '22 01:09

Maurício Linhares