import java.io.File; import org.apache.commons.io.FileUtils; public class ListFilesExample { public static void main(String[] args) { File directory = new File("/path/to/directory"); String[] extensions = {"txt", "pdf", "docx", "xlsx"}; // filter by file extensions boolean recursive = true; Collectionfiles = FileUtils.listFiles(directory, extensions, recursive); for (File file : files) { System.out.println(file.getName()); } } }
import java.io.File; import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; import org.apache.commons.io.FileUtils; public class DeleteOldFilesExample { public static void main(String[] args) { File directory = new File("/path/to/directory"); boolean recursive = true; CollectionIn both examples, we are using the FileUtils(listFiles) method to retrieve a list of all files in a directory. The first example simply displays the name of each file, while the second example deletes any files that are older than 30 days. These examples are part of the Apache Commons IO library.files = FileUtils.listFiles(directory, null, recursive); Instant now = Instant.now(); Instant threshold = now.minus(30, ChronoUnit.DAYS); // older than 30 days for (File file : files) { Instant lastModified; try { lastModified = Instant.ofEpochMilli(file.lastModified()); } catch (Exception e) { continue; } if (lastModified.isBefore(threshold)) { try { FileUtils.forceDelete(file); } catch (IOException e) { System.err.println("Failed to delete file: " + file.getAbsolutePath()); } } } } }