Q: Create a temporary directory in Java


D: Is there a standard and reliable way of creating a temporary directory inside a Java application? There's an entry in Sun'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.)

Test Case #11


File ID: #617438-0-cc


public static File createTempDirectory() throws IOException {
        final File temp;
        temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
        if (!temp.delete()) {
            throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
        }
        if (!temp.mkdir()) {
            throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
        }
        return temp;
    }

  1. Java is known not to delete files immediately. That's true, even if you do not open it. So, a more safe way is `temp.delete(); temp = new File(temp.getPath + ".d""); temp.mkdir(); ..., temp.delete();`.
  2. This code has a race condition between `delete()` and `mkdir()`: A malicious process could create the target directory in the meantime (taking the name of the recently-created file). See [`Files.createTempDir()`](http://guava-libraries.googlecode.com/svn/tags/release08/javadoc/com/google/common/io/Files.html#createTempDir%28%29) for an alternative.
  3. To add to Joachin Sauers' comment: e.g. on linux, inotify on /tmp will tell you the names of all created and deleted files. It is trivial for an attacker, a user on the same machine, to cause the process using this function to write to arbitrary file accessible by the victim.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: