Domanda

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)?

È stato utile?

Soluzione

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.

Altri suggerimenti

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");

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top