Java - Create temporary file/directory


A temporary file/directory is not automatically deleted.

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


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*/