I can not find anywhere that specificity explain what can be store inside of String[] cmdarray of Process exec(String[] cmdarray) method. I found some places cmdarray to store an array command or location of file and remote server name. So I wonder what exactly we can store inside of String[] cmdarray?
- 12,410
- 3
- 41
- 67
- 456
- 12
- 28
2 Answers
The first element of the array is the command, such as cmd. The others are arguments. For example:
try {
Process p = Runtime.getRuntime().exec(new String[] {"cmd", "/c", "echo", "This", "is", "an", "argument"});
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while((s = reader.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
Here "/c", "echo", "This", "is", "an", and "argument" are all arguments for the command cmd. The output is:
This is an argument
If you want to run multiple commands, you must use a double ampersand to indicate that another command is starting:
try {
Process p = Runtime.getRuntime().exec(new String[] { "cmd", "/c", "echo", "This", "is", "an", "argument",
"&&", "echo", "this", "command", "snuck", "in" });
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
Here each command is being sent to cmd. I'm not positive, but I believe you must start a new process to send commands elsewhere. The output is:
This is an argument
this command snuck in
Read this for more info: https://stackoverflow.com/a/18867097/5645656
- 2,749
- 3
- 21
- 42
-
Then, then can it be a list of commands such as "cmd", "cmd", "cmd" ? – RLe Dec 28 '17 at 17:35
-
Yes, if you look at [this answer](https://stackoverflow.com/a/18867097/5645656), you'll see that adding a double ampersand will mark the end of each command the beginning of the next. – Cardinal System Dec 28 '17 at 17:37
-
My pleasure! =) – Cardinal System Dec 28 '17 at 23:15
According to docs:
Executes the specified command and arguments in a separate process.
Consider it as your command line interface inside JVM. It takes all process names that can be invoked using CMD. For eg: you can pass String chromium to exec in Ubuntu and you will notice that chromium is launched.
- 12,410
- 3
- 41
- 67