Peter Becker Peter Becker - 1 year ago 130
Java Question

How to create a temporary directory/folder in Java?

Is there a standard and reliable way of creating a temporary directory inside a Java application? There's an entry in Java's issue database, which has a bit of code in the comments, but I wonder if there is a standard solution to be found in one of the usual libraries (Apache Commons etc.) ?

Answer Source

If you are using JDK 7 use the new Files.createTempDirectory class to create the temporary directory.

Before JDK 7 this should do it:

public static File createTempDirectory()
    throws IOException
    final File temp;

    temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

        throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());

        throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());

    return (temp);

You could make better exceptions (subclass IOException) if you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download