Monday, February 21, 2005

Using varargs for path names

A handy pair of utility methods:

public static <T> String join(final T separator,
        final T first, final T... rest) {
    final StringBuffer buf = new StringBuffer();


    for (int i = 0; i < rest.length; ++i)

    return buf.toString();


public static String makePath(final String root, final String... children) {
    return join(File.separator, root, children);

No more junk like node + File.separator + subNode + File.separator + fileName when I can call makePath(node, subNode, fileName).

UPDATE: See the Jakarta Commons Lang version of join(Object[], String) and friends. Unfortunately it predates JDK 5 and varargs by enough that the designer didn't place the separator argument first in the list instead of last.

Post a Comment