Wednesday, February 02, 2005

Methods I cannot do without

In almost any project I work on I wind up writing certain methods over and over again. High among them are:

public static void copyAndClose(final InputStream in, final OutputStream out)
        throws IOException {
    try {
        // CopyUtils is from Jakarta IO
        CopyUtils.copy(in, out);
        out.flush();

    } finally {
        try {
            out.close();

        } finally {
            in.close();
        }
    }
}

public static File createTemporary(final String prefix) {
    final File tmp = File.createTempFile(prefix, null);

    tmp.deleteOnExit();

    return tmp;
}

Perhaps I can persuade Jakarta IO to take on copyAndClose, but there seems low odds of the JDK including createTemporary.

1 comment:

Benjamin Francisoud said...

I do agree with you too, but I've got an other problem with IO package.
Usually I can spend 4 or 6 month not using IO package, everytime I start to use it again I always get confuse by the api (ByteArrayInputStream, BufferedLineReaderInputStream, FileWriterOutputStream... or whatever).
After 1 or 2 days, everything's returned to normal but I don't feel productive.