Nick Sanders
Nick Sanders

Reputation: 703

Java runtime exec

I am trying to do something using system exec in Java

Runtime.getRuntime().exec(command);

Surprisingly everything that is related with paths, directories and files is not working well

I don't get why and just want to know is there any alternatives?

Upvotes: 0

Views: 833

Answers (3)

Edward Falk
Edward Falk

Reputation: 10063

The exec() method can take three arguments. The third is the directory your subprocess should use as its working directory. That solves your "cd" problem, anyway.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272217

As noted above, cd is a shell builtin. i.e. it's not an executable. You can determine this using:

$ which cd
cd: shell built-in command

As it's not a standalone executable, Runtime.exec() won't be able to do anything with it.

You may be better off writing a shell script to do the shell-specific stuff (e.g. change the working directory) and then simply execute that shell script using Runtime.exec(). You can set PATH variables etc. within your script and leave Java to simply execute your script.

One thing that catches people out is that you have to consume your script's stdout/stderr (even if you throw it away). If you don't do this properly your process will likely block. See this SO answer for more details.

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

The alternative is to use the ProcessBuilder class, which has a somewhat cleaner interface, but your main problem is probably related to how the OS processes command lines, and there isn't much Java can do to help you with that.

Upvotes: 4

Related Questions