Deleting a Temporary File with DELETE_ON_CLOSE - Java File Path IO

Java examples for File Path IO:File Permission

Description

Deleting a Temporary File with DELETE_ON_CLOSE

Demo Code

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

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 = null;//from   w  w w . j a  va 2 s  .co m
    try {
      tmp_file = Files.createTempFile(basedir, tmp_file_prefix, tmp_file_sufix);
    } catch (IOException e) {
      System.err.println(e);
    }
    try (OutputStream outputStream = Files.newOutputStream(tmp_file,
        StandardOpenOption.DELETE_ON_CLOSE);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            outputStream))) {

      Thread.sleep(10000);
    } catch (IOException | InterruptedException e) {
      System.err.println(e);
    }
  }
}

Related Tutorials