Delete File Example
This program demonstrates deleting a file.
Problem Statement
Write a Java program that deletes a file if it exists.
Source Code
| 1 | import java.io.*; |
| 2 | public class FileDeleteExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq File Delete Example"); |
| 5 | File f=new File("delete.txt"); |
| 6 | if(f.exists()){ |
| 7 | if(f.delete()){ |
| 8 | System.out.println("Eduinq File Deleted Successfully"); |
| 9 | } else { |
| 10 | System.out.println("Eduinq Exception: File Deletion Failed"); |
| 11 | } |
| 12 | } else { |
| 13 | System.out.println("Eduinq Exception: File Not Found"); |
| 14 | } |
| 15 | } |
| 16 | } |
Program Output
Eduinq File Delete Example Eduinq Exception: File Not Found
Explanation
File deletion uses File.delete() method. - Checks existence before deletion to avoid errors. - Provides meaningful feedback for success/failure. - In enterprise systems, deletion is used for cleanup tasks. Conclusion: Shows deleting a file safely.