Simulate a temporary file by adding DELETE_ON_CLOSE option in CREATE option - Java File Path IO

Java examples for File Path IO:File Permission

Description

Simulate a temporary file by adding DELETE_ON_CLOSE option in CREATE option

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 {

    String tmp_file_prefix = "test_";
    String tmp_file_sufix = ".txt";
    Path tmp_file = null;//  ww  w. j ava2 s  .  c o m

    tmp_file = FileSystems.getDefault().getPath("C:/folder1/tmp",
        tmp_file_prefix + "temporary" + tmp_file_sufix);

    try (OutputStream outputStream = Files.newOutputStream(tmp_file,
        StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            outputStream))) {

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

  }
}

Result


Related Tutorials