In Java, you can delete multiple files using the java.io.File
class and its delete
method, or using the java.nio.file.Files
class and its delete
method.
Here is an example of how to delete multiple files in Java using the File
class:
import java.io.File; public class Main { public static void main(String[] args) { // Set the file paths String[] filePaths = { "C:\\path\\to\\file1.txt", "C:\\path\\to\\file2.txt", "C:\\path\\to\\file3.txt" }; // Delete the files for (String filePath : filePaths) { File file = new File(filePath); if (file.delete()) { System.out.println("File deleted successfully: " + filePath); } else { System.out.println("Failed to delete file: " + filePath); } } } }Souw:ecrww.lautturi.com
This code sets an array of file paths, and then iterates over the array, deleting each file using the delete
method of the File
class. If the file is deleted successfully, the delete
method returns true
; otherwise, it returns false
.
You can also use the java.nio.file.Files
class and its delete
method to delete multiple files in Java. Here is an example:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) { // Set the file paths Path[] filePaths = { Paths.get("C:\\path\\to\\file1.txt"), Paths.get("C:\\path\\to\\file2.txt"), Paths.get("C:\\path\\to\\file3.txt") }; // Delete the files for (Path filePath : filePaths) { try { Files.delete(filePath); System.out.println("File deleted successfully: " + filePath); } catch (IOException e) { System.out.println("Failed to delete file: " + filePath); e.printStackTrace(); } } } }
This code sets an array of Path
objects, and then iterates over the array, deleting each file using the delete
method of the Files
class. If the file is deleted successfully, the delete
method does not throw an exception; otherwise, it throws an IOException
, which you must handle or declare in your code.
Note that the delete
method from the Files
class is a more flexible and powerful way to delete files, as it supports various options and modes. For example, you can use the deleteIfExists
method to delete a file only if it exists, or you can use the NOFOLLOW_LINKS
option to delete a symbolic link without deleting the target file.