How to delete temporary file in Java?

creating temporary file in java and delete it.

First Example:

by calling deleteOnExit the temp file is deleted when the jvm is shut down.

package com.nourit.javaIO;

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

public class DeleteTempFileExample {

  public static void main(String[] args) {
    try{
      	   //create a temp file
      	   File temp = File.createTempFile("nouritTempfile", ".tmp");
      	   System.out.println("Temporary file : " + temp.getAbsolutePath());
      	   //delete temporary file 
      	   temp.deleteOnExit();
      	   if(temp.exists() && !temp.isDirectory()){
      		   System.out.println("Temporary file : " + temp.getAbsolutePath() + " Deleted");
      	   }
      	}catch(IOException e){

      	   e.printStackTrace();

      	}

  }

}

Output:

Temporary file : C:\Users\Nour-it\AppData\Local\Temp\nouritTempfile8907862065968404250.tmp
Temporary file : C:\Users\Nour-it\AppData\Local\Temp\nouritTempfile8907862065968404250.tmp Deleted

 

 

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*