views:

96

answers:

2

I have a method like the following:

public void launch(String cmd, String [] args, String workingDir)

Inside this method I call ProcessBuilder.

How can I call ProcessBuilder including an arbitrary number of args included in my args parameter?

E.g., something like this:

ProcessBuilder pb = new ProcessBuilder(cmd, args);

I notice ProcessBuilder does have this contructor:

ProcessBuilder(List<String> command) 

Maybe I could use that somehow.

+7  A: 

ProcessBuilder has a varargs Constructor - ProcessBuilder(String... command) - so you can use that, but you'll need to make your command and arguments into a single array.

Otherwise you can use the other Constructor as follows:

List<String> list = new ArrayList<String>(args.length + 1);
list.add(cmd)
list.addAll(Arrays.asList(args));
ProcessBuilder pb = new ProcessBuilder(list);
Dave Webb
+7  A: 

How about:

public static void launch(String cmd, String[] args, String workingDir) {
    List<String> strArgs = new ArrayList<String>();
    strArgs.add(cmd);
    strArgs.addAll(Arrays.asList(args));
    ProcessBuilder pb = new ProcessBuilder(strArgs);
}
Bozho