开发者

Java - How to Give method an array

开发者 https://www.devze.com 2023-01-10 13:14 出处:网络
I have a method like the following: public void launch(String cmd, String [] args, String workingDir) Inside this method I call ProcessBuilder.

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.


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);


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消