Deleting a Temporary File with Shutdown-Hook - Java File Path IO

Java examples for File Path IO:File Permission

Description

Deleting a Temporary File with Shutdown-Hook

Demo Code

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) throws Exception {
    Path basedir = FileSystems.getDefault().getPath("C:/folder1/tmp");
    String tmp_file_prefix = "test_";
    String tmp_file_sufix = ".txt";

    Path tmp_file = Files.createTempFile(basedir, tmp_file_prefix,
        tmp_file_sufix);/*from   ww  w  .ja v a  2  s  .co m*/

    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        System.out.println("Deleting the temporary file ...");

        try {
          Files.delete(tmp_file);
        } catch (IOException e) {
          System.err.println(e);
        }

        System.out.println("Shutdown hook completed...");
      }
    });

    Thread.sleep(10000);

  }
}

Related Tutorials