How to delete specific files from a folder in Java?
To remove specific files in a folder, you can use the File class and recursive method in Java. Here is an example code:
import java.io.File;
public class DeleteFilesInFolder {
public static void main(String[] args) {
String folderPath = "path/to/folder";
String fileName = "file.txt";
deleteFileInFolder(folderPath, fileName);
}
public static void deleteFileInFolder(String folderPath, String fileName) {
File folder = new File(folderPath);
if (folder.exists() && folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().equals(fileName)) {
file.delete();
System.out.println(file.getName() + " deleted.");
} else if (file.isDirectory()) {
deleteFileInFolder(file.getAbsolutePath(), fileName);
}
}
}
}
}
}
Please replace the folderPath variable with the path to the folder containing the files to be deleted, and replace the fileName variable with the name of the file to be deleted. This code will search and delete all files with the specified file name in the specified folder and its subfolders.