gautam
gautam

Reputation: 197

Executing .exe file from java

I want to run a .exe file from my java code,along with passing few arguments/options to the .exe file.

So basically, I did following:

BufferedReader br = null;
OutputResult out = new OutputResult();

String commandStr= "cmd.exe /C A-B/xyz.exe health -U admin -P admin";
Process p = Runtime.getRuntime().exec(commandStr);

br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
    out.add(line.trim());
}

NOTE: Here A-B is name of the directory in which xyz.exe is located.

But when the variable out is printed, it actually shows that it has nothing.

So instead of above code I modified it to the following:

BufferedReader bre = null;
OutputResult oute = new OutputResult();

String commandStr= "cmd.exe /C A-B/xyz.exe health -U admin -P admin";
Process p = Runtime.getRuntime().exec(commandStr);

bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bre.readLine()) != null) {
    oute.add(line.trim());
}

Now here when the variable oute is printed, it shows the message,

'A-B' is not recognized as an internal or external command, operable program or batch file.

So my question is that why A-B is not being treated as a directory inside which the actual .exe file resides.

Please resolve the error if any one knows about this problem.

Upvotes: 0

Views: 89

Answers (2)

Artem Novikov
Artem Novikov

Reputation: 4625

You should use a full path to your target xyz.exe - when you execute cmd.exe like that, it's not relative to the folder of your Java program, it's relative to C:\Windows\System32 therefore it can't see your A-B folder.

So, for example: cmd.exe /C C:/A-B/xyz.exe health -U admin -P admin

And as @CSK correctly noticed, you can execute your .exe directly, without cmd.exe. For examle:

Process process = new ProcessBuilder("C:/A-B/xyz.exe", "health", "-U", "admin", "-P", "-admin").start();

Upvotes: 1

user6447966
user6447966

Reputation:

I know that, for example, Java on Raspbian can't access directories with a space (for example /New Folder). I guess its some problem about how Raspbian considers the ' ' char when creating directory. Possibly, Windows might have the same problem with the '-' char. Can you rename the directory without any such chars and try again?

(I use a Mac so I'm unable to recreate the problem. Another option can be, if this is in fact not a problem to do with chars, to create a shell script from which the exe is executed and instead run this script via Java. I am only advising this because I used this method before without any problems.)

Upvotes: 0

Related Questions