Java Delete File
There are two techniques to erase a record in Java:
- Utilizing File.delete() technique.
- Utilizing File.deleteOnExit() technique.
Using File.delete() technique:
In Java, we can erase a document by utilizing the File.delete() technique for File class. The delete() technique erases the record or index meant by the theoretical pathname. On the off chance that the pathname is an index, that registry should be vacant to erase.
The strategy mark is:
public boolean delete()
The strategy returns valid in the event that the document or catalog erased effectively, in any case gets back false.
//program for understanding
import java.io.File;
public class DeleteFile1
{
//main method
public static void main(String[] args)
{
try
{
Document f= new File("E:\\demo1.txt"); //record to be erase
if(f.delete())//returns Boolean worth
{
System.out.println(f.getName() + " deleted");//getting and printing the document name
}
else
{
System.out.println("failed");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Using File.deleteOnExit() technique:
The File.deleteOnExit() technique likewise erases the document or index characterized by unique pathname.
The deleteOnExit() strategy erases document backward request. It erases the document when JVM ends. It returns no worth. When the solicitation has been made, dropping the request is unimaginable.
So this technique ought to be utilized with care.
The technique mark is:
public void deleteOnExit()
As a rule, we utilize this technique when we need to erase the transitory document. A brief document is utilized to store the less significant and transitory information, which ought to continuously be erased when JVM ends.(JVM – Java Virtual Machine)
If we have any desire to erase the temp record physically, we can utilize File.delete() strategy.
//program for understanding
import java.io.File;
import java.io.IOException;
public class DeleteOnExitExample
{
public static void main(String[] args)
{
Record temp;
Try
{
temp = File.createTempFile("abc", ".temp");//making a .temp record
System.out.println("Temp record made at area: " + temp.getAbsolutePath());
temp.deleteOnExit();//erase record on runtime exit
System.out.println("Temp document exists : " + temp.exists());
}
get (IOException e)
{
e.printStackTrace();
}
}
}