import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; public class FileDeletionExample { public static void main(String[] args) { try { Path path = Paths.get("C:\\Users\\UserName\\Desktop\\test.txt"); // Replace with your file path Files.delete(path); System.out.println("File deleted successfully."); } catch (IOException e) { System.out.println("Failed to delete the file: " + e.getMessage()); } } }
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileDeletionExample { public static void main(String[] args) { try { Path directory = Paths.get("C:\\Users\\UserName\\Desktop\\myDirectory"); // Replace with your directory path Files.walk(directory).map(Path::toFile).forEach(File::delete); System.out.println("Directory deleted successfully."); } catch (IOException e) { System.out.println("Failed to delete the directory: " + e.getMessage()); } } }In this example, we are deleting a directory named "myDirectory" located on the desktop. The walk() method is called on the Files class, passing the path of the directory to be deleted as a parameter, and a stream of all the files in the directory is created. Then, the delete() method is called on each file to delete all the files in the directory first, followed by deleting the directory itself. The Files class is part of the java.nio.file package library which was introduced in Java 7.