In this section, we will present a source that would show how to delete a temporary or temp file in java.  The source code is very simple, it does make use of method deleteOnExit() of File class under java.io package.

Java Source Code to Delete Temporary or Temp file

The method deleteOnExit() enable us to clean up the generated temporary file once the program exits. This is necessary in cleaning up the clutter during runtime. We don’t want unnecessary file that we no longer need to be kept on our machine.

package com.javatutorialhq.tutorial;

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

public class DeleteTempFile {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		File fTemp;
		try {
			fTemp = File.createTempFile("ems-status", "tmp");
			fTemp.deleteOnExit();
			System.out.println("Temporary File "+fTemp.getAbsolutePath()+" deleted");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Sample Output:

Temporary File C:\Users\ryan\AppData\Local\Temp\ems-status7197441587941385065tmp deleted