Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to Give method an array

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.

like image 276
Greg Avatar asked Jan 22 '26 00:01

Greg


2 Answers

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);
like image 129
Dave Webb Avatar answered Jan 24 '26 15:01

Dave Webb


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);
}
like image 37
Bozho Avatar answered Jan 24 '26 13:01

Bozho