In Java, we can use the NIO Files.delete() or Files.deleteIfExists() to delete a temporary file, it works the same like delete a regular text file.

  // create a temporary file
  Path path = Files.createTempFile(null, ".log");
  // delete
  Files.delete(path);

  // or
  if(Files.deleteIfExists(path)){
    // success
  }else{
    // file does not exist
  }

1. Delete Temporary File – Java NIO

This example uses java.nio to create a temporary file, write a line, and delete it.

TempFileDelete1.java

package com.favtuts.io.temp;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class TempFileDelete1 {

    public static void main(String[] args) {

        try {

            Path temp = Files.createTempFile(null, ".log");
            System.out.println(temp);

            // if file doesn't exist throws NoSuchFileException
            // Files.delete(temp);

            // write a line
            Files.write(temp, "Hello World".getBytes(StandardCharsets.UTF_8));

            // check if file exists before delete
            boolean result = Files.deleteIfExists(temp);
            if (result) {
                System.out.println("File is success delete.");
            } else {
                System.out.println("File doesn't exist.");
            }

        } catch (IOException e) {
            System.err.println("Unable to delete the file!");
            e.printStackTrace();
        }

    }

}

Output

/tmp/16821893865655843803.log
File is success delete.

2. Delete Temporary File – Java IO

This example uses the legacy IO java.io to create a temporary file, and delete it later.

TempFileDelete2.java

package com.favtuts.io.temp;

import java.io.File;
import java.io.IOException;

public class TempFileDelete2 {

    public static void main(String[] args) {

        try {

            File tempFile = File.createTempFile("abc_", ".log");
            System.out.println(tempFile);

            boolean result = tempFile.delete();
            if (result) {
                System.out.println(tempFile.getName() + " is deleted!");
            } else {
                System.out.println("Sorry, unable to delete the file.");
            }

            // delete when JVM exit normally.
            // tempFile.deleteOnExit();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

The file.deleteOnExit() will delete the temporary file only if “JVM exit normally” uses it with care.

Note

The legacy IO has some drawbacks, if possible, always picks the new Java NIO java.nio.* for file IO stuff.

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/temp

References

Leave a Reply

Your email address will not be published. Required fields are marked *