Temporary files and directories in Java 7 and before

Sometimes we want to create a temporary file, whether to save some data that gets written by some other application or just to temporary store stuff. Well, usually applications have their own temporary folder where they do this and it gets somehow configured. But why not use the underlying OS specific file like "/tmp/" in Linux so there must be some system property that has this info and there is. The key is "java.io.tmpdir" resulting in "/tmp" in my case or by code:

String tempDir = System.getProperty("java.io.tmpdir");

We can use tempDir  folder as a temporary place to store files, but there are a lot nicer ways to work with files like this even in JDK6 not just in JDK7:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class TempFile {

   public static void main(String[] args) {

    try {
      // create a temp file
      File tempFile = File.createTempFile("old-file", ".tmp");
      System.out.println("Temp file : " + tempFile.getAbsolutePath());
      // nio style
      final Path path = Files.createTempFile("nio-temp", ".tmp");
      System.out.println("Temp file : " + path);
      //call the same delete on exit

      Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
          try {
            System.out.println("deleted file at "+path);
          } catch (IOException e) {

    } catch (IOException e) {




The JDK 7 way is the use the Files class and use Path 's that can easily enable us way to create and work files and their attributes and permissions. Calling tempFile.deleteOnExit() or path.toFile().deleteOnExit() will enable the files to be deleted automatically after the virtual machine terminates. Files are deleted in the reverse order that they are registered and besides that we need to be careful about what the path is.
Deletion will only happen if JVM is closed under normal condition and not for example using kill -9 (SIGKILL) under Linux.

One other interesting option is to do the deletion with a shutdown hook using "Runtime.getRuntime().addShutdownHook(new Thread() {...}" that registers  a new virtual-machine shutdown hook. This shutdown hook is simply an initialized thread, but it is not started. The thread will only be executed when the virtual machine begins its shutdown sequence during normal shutdown.

Related Links

Popular Posts