Let’s learn java delete file.
Java delete file
To delete a file in java delete() method of File class is used. delete() method deletes the file or directory denoted by this abstract pathname.
Syntax:
public boolean delete()
Returns:
true if and only if the file or directory is successfully deleted; false otherwise. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Here’s the program to delete a file.
import java.io.File; public class JavaDeleteFileExample { public static void main(String[] args) { File fl = new File("demo.txt"); if(fl.delete()) { System.out.println(fl.getName() + " file deleted."); } else { System.out.println("Failed to delete file."); } } }
Output:
demo.txt file deleted
Similarly we can delete a folder using delete() method of File class.
NOTE: In order to delete a folder using delete() method the folder must be empty.
Let’s see an example to delete folder using delete() method of File class.
import java.io.File; public class JavaDeleteFolderExample { public static void main(String[] args) { File fl = new File("D:\project\Employee\details"); if(fl.delete()) { System.out.println(fl.getName() + " folder deleted."); } else { System.out.println("Failed to delete folder."); } } }
Output:
details folder deleted.
Now let’s learn to delete a file using deleteIfExists(Path path) method of java.nio.file.Files class.
deleteIfExists(Path path) method deletes a file if it exists. As with the delete(Path) method, an implementation may need to examine the file to determine if the file is a directory. If the file is a directory then the directory must be empty.
Syntax:
public static boolean deleteIfExists(Path path) throws IOException
Parameters:
path the path to the file to delete
Returns:
true if the file was deleted by this method; false if the file could not be deleted because it did not exist.
Throws:
DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not empty (optional specific exception).
IOException – if an I/O error occurs.
Now let’s see an example on deleteIfExists(Path path) method.
import java.io.IOException; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Paths; public class DeleteIfExistsExample { public static void main(String[] args) { try { Files.deleteIfExists(Paths.get("D:\Project\Sachin\JavaPrograms\demo.txt")); } catch(NoSuchFileException e) { System.out.println("No such file exists"); } catch(DirectoryNotEmptyException e) { System.out.println("Directory is not empty."); } catch(IOException ex) { System.out.println("Invalid permission."); } System.out.println("Deleted successfully."); } }
Output:
Deleted successfully.
Also read – HashSet in java