2

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?

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
RLe
  • 456
  • 12
  • 28

2 Answers2

3

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

Cardinal System
  • 2,749
  • 3
  • 21
  • 42
2

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.

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67