Java - Create temporary file/directory

Introduction

A temporary file/directory is not automatically deleted.

You may want to use the deleteOnExit() method of the java.io.File class to delete the file when the JVM exits.

Demo

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

public class Main {
  public static void main(String[] args) throws IOException {
    Path tempFile = Files.createTempFile("myTempFile", ".txt");

    // Delete the file when the JVM exits
    tempFile.toFile().deleteOnExit();/*from  ww  w.  ja v a 2  s  .co m*/
  }
}