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

    buf.append(first);

    for (int i = 0; i < rest.length; ++i)
        buf.append(separator).append(rest[i]);

    return buf.toString();
}

And:

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.

No comments: