I am trying to execute command line arguments via Java. For example:
// Execute command
String command = \"cmd /c start cmd.exe\";
Process child = Runtime.ge
Try this link
You do not use "cd" to change the directory from which to run your commands. You need the full path of the executable you want to run.
Also, listing the contents of a directory is easier to do with the File/Directory classes
Each of your exec calls creates a process. You second and third calls do not run in the same shell process you create in the first one. Try putting all commands in a bat script and running it in one call:
rt.exec("cmd myfile.bat");
or similar
try {
String command = "Command here";
Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + command);
} catch (IOException e) {
e.printStackTrace();
}
This because every runtime.exec(..)
returns a Process
class that should be used after the execution instead that invoking other commands by the Runtime
class
If you look at Process doc you will see that you can use
getInputStream()
getOutputStream()
on which you should work by sending the successive commands and retrieving the output..
Every execution of exec
spawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its own working directory and then exit (i.e. it's effectively a no-op).
If you want to compose requests, you'll need to do this within a single call to exec
. Bash allows multiple commands to be specified on a single line if they're separated by semicolons; Windows CMD may allow the same, and if not there's always batch scripts.
As Piotr says, if this example is actually what you're trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:
String[] filenames = new java.io.File("C:/").list();
Here is a simpler example that does not require multiple threads:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SimplePty
{
public SimplePty(Process process) throws IOException
{
while (process.isAlive())
{
sync(process.getErrorStream(), System.err);
sync(process.getInputStream(), System.out);
sync(System.in, process.getOutputStream());
}
}
private void sync(InputStream in, OutputStream out) throws IOException
{
while (in.available() > 0)
{
out.write(in.read());
out.flush();
}
}
public static void main( String[] args ) throws IOException
{
String os = System.getProperty("os.name").toLowerCase();
String shell = os.contains("win") ? "cmd" : "bash";
Process process = new ProcessBuilder(shell).start();
new SimplePty(process);
}
}