Friday, April 1, 2016

Java I/O Examples : How To Delete Temporary File

Intro


This examples will demonstrates how to delete a temporary file using Java program. To delete it, you can use one of the following method:
  • deleteOnExit(), delete temporary file when program is terminated or exited.
  • delete(), delete temporary file imediately,

Examples


package com.freesamplecode.java.io;

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

public class DeleteTemporaryFileDemo {
	public static void main(String[] args){
		
		try {
			
			// create temporary file "test.tmp"
			
			File tempFile = File.createTempFile("test", ".tmp");
			
			
			// delete temporary file when the program is terminated or existed
			
			tempFile.deleteOnExit();
			
			//delete temporary file immediately
			
            //tempFile.delete();
			
			System.out.println("Temporary file "+tempFile.getName() + " is successfully deleted");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


Output


Temporary file test1195400416650249998.tmp is successfully deleted

How To Delete Temporary File In Java

0 comments: