Java Delete Files

❌ Java Delete Files

Java allows deleting files using:

  1. File.delete() (Old, simple method)

  2. Files.delete() or Files.deleteIfExists() (Modern, Java NIO)


1. Delete a File Using File.delete()


 

  • Returns true if deletion is successful, false otherwise.

  • Does not throw an exception if file does not exist.


 2. Delete a File Using Files.delete() (NIO)


 

  • Throws an exception if file does not exist.

  • Useful for exception handling and modern Java applications.


 3. Delete a File If It Exists

Use Files.deleteIfExists() to avoid exceptions if the file is missing.


 


 4. Delete a Directory and Its Contents


 

  • Must delete all files inside before deleting the directory.

  • For modern NIO recursive delete, use Files.walk() (advanced).


🧠 Summary Table

Method Package Notes
File.delete() java.io Simple, returns boolean
Files.delete() java.nio Modern, throws exception if file missing
Files.deleteIfExists() java.nio Modern, avoids exception if file missing

Best Practice

  • Use NIO (Files.delete()) for modern Java programs.

  • Always handle exceptions to avoid unexpected crashes.

You may also like...