In Java, you can delete files using the java.io.File
class or the java.nio.file.Files
class. Both approaches provide methods to delete files. Here's how you can delete files using each approach:
java.io.File
import java.io.File; public class DeleteFile { public static void main(String[] args) { File file = new File("example.txt"); // Check if file exists before deleting if (file.exists()) { if (file.delete()) { System.out.println("File deleted successfully."); } else { System.out.println("Failed to delete the file."); } } else { System.out.println("File doesn't exist."); } } }
java.nio.file.Files
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; public class DeleteFileNIO { public static void main(String[] args) { Path path = Paths.get("example.txt"); try { Files.delete(path); System.out.println("File deleted successfully."); } catch (IOException e) { System.out.println("Failed to delete the file: " + e.getMessage()); } } }
delete()
method returns true
if the file is successfully deleted and false
otherwise. With NIO, an exception is thrown if the file cannot be deleted.java.io.File
is the older approach and provides basic file manipulation operations.java.nio.file.Files
is part of the New I/O (NIO) API introduced in Java 7 and provides more powerful and flexible file operations.