0

The following doesn't work in Java (an exception is thrown):

Runtime.getRuntime().exec("cd mydir; myprog");

The same works fine in PHP:

exec("cd mydir; myprog");

What exactly is different in Java's implementation and why (it seems more limited at first glance)?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ree
  • 6,061
  • 11
  • 48
  • 50

3 Answers3

2

the java exec command does not use the system command interpreter. something like "cd mydir; myprog" depends on the system command line interpreter (e.g. on windows cmd, on linux sh) to split that into 2 separate commands and execute each of them. java does not invoke the system command interpreter, so that does not work. you either need to call each command separately, or invoke the desired interpreter yourself as part of the command line.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • All right, but I wonder why it's implemented that way? Why not use the command interpreter like, say, PHP does? It looks like an unnecessary limitation to me. – Ree Dec 11 '11 at 18:04
  • depending on the help of a command line interpreter would probably conflict with java's attempts to be platform agnostic. obviously, when you call exec, you're probably already out of that realm... in general, java has been reluctant to allow "raw" access to the underlying OS, and when provided, generally at the "most basic" level. in this case, the "most basic" level is allowing you to execute straight commands. – jtahlborn Dec 11 '11 at 19:00
0

I've seen people have problems like this, and I'm sure there are several ways, however the one I've seen most people reply is this. add cmd before it.

Runtime.getRuntime().exec("cmd cd mydir; myprog");
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
D3_JMultiply
  • 1,022
  • 2
  • 12
  • 22
-1

Assuming you're running an applet, not Java in a CLI environment on the server? If so, then your Java runtime is running on the client computer, not the server.

Java also has a better way to handle multiple commands than your semicolon. Instead of using the signature:

Runtime.exec(String)

try using this for each of your commands:

Runtime.exec(String[])

and make each argument of your command an element in the String array.

Keith B.
  • 11
  • 2