Java File example to delete a file from directory using delete
By candid | Posted :
Nov 22, 2016
| Updated :
Nov 22, 2016
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
Program:
package com.candidjava;
import java.io.*;
public class FileDelete
{
public static void main(String[] args)
{
File f = null;
Boolean bool = false;
try
{
f = new File("mmn.txt");
bool = f.delete();
System.out.println("file deleted: " + bool);
f.createNewFile();
System.out.println("create new file method is invoked");
bool = f.delete();
System.out.println("file deleted:" + bool);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:
file deleted: false
create new file method is invoked
file deleted: true
Description:
Initially the file is not created,so the delete method returns false.After creation of file,delete method returns true.
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file