Deleting a Temporary Directory with the deleteOnExit() Method - Java File Path IO

Java examples for File Path IO:File Permission

Introduction

deleteOnExit() Method will delete the passed file or directory when the JVM shuts down.

Demo Code

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

public class Main {
  public static void main(String[] args) {
    Path basedir = FileSystems.getDefault().getPath("C:/folder1/tmp/");
    String tmp_dir_prefix = "test_";
    try {/*from   w  ww .j a va2  s .c  o  m*/
      // create a tmp directory in the base dir
      Path tmp_dir = Files.createTempDirectory(basedir, tmp_dir_prefix);
      File asFile = tmp_dir.toFile();
      asFile.deleteOnExit();
      Thread.sleep(10000);
    } catch (IOException | InterruptedException e) {
      System.err.println(e);
    }

  }
}

Result


Related Tutorials