1. import java.io.File;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.concurrent.atomic.AtomicInteger;
  6. public class DirectoryDataFilter {
  7. private final File rootDir;
  8. private final int maxRetries;
  9. private final AtomicInteger retryCount = new AtomicInteger(0);
  10. public DirectoryDataFilter(File rootDir, int maxRetries) {
  11. this.rootDir = rootDir;
  12. this.maxRetries = maxRetries;
  13. }
  14. public List<String> filterData() throws IOException {
  15. List<String> filteredData = new ArrayList<>();
  16. File[] files = rootDir.listFiles();
  17. if (files != null) {
  18. for (File file : files) {
  19. try {
  20. String data = processFile(file); // Process each file
  21. if (data != null && !data.isEmpty()) {
  22. filteredData.add(file.getAbsolutePath() + ": " + data);
  23. }
  24. } catch (IOException e) {
  25. if (retryCount.get() < maxRetries) {
  26. retryCount.incrementAndGet();
  27. try {
  28. System.err.println("Retry processing " + file.getName() + " (attempt " + retryCount.get() + ")");
  29. processFile(file); // Retry processing
  30. } catch (IOException retryException) {
  31. System.err.println("Failed to process " + file.getName() + " after " + maxRetries + " retries.");
  32. // Handle failure - e.g., log, skip, or throw an exception
  33. }
  34. } else {
  35. System.err.println("Failed to process " + file.getName() + " after " + maxRetries + " retries.");
  36. // Handle failure - e.g., log, skip, or throw an exception
  37. }
  38. }
  39. }
  40. }
  41. return filteredData;
  42. }
  43. private String processFile(File file) throws IOException {
  44. // Simulate data processing - replace with your actual logic
  45. if (file.getName().endsWith(".txt")) {
  46. return "Data from " + file.getName();
  47. } else if (file.getName().endsWith(".log")) {
  48. return "Log data from " + file.getName();
  49. } else {
  50. return null; // Return null if file type is not supported
  51. }
  52. }
  53. public static void main(String[] args) throws IOException {
  54. // Example usage:
  55. File rootDirectory = new File("test_dir"); // Replace with your directory
  56. File[] files = new File[] { rootDirectory, rootDirectory.mkdir() };
  57. // Create some dummy files
  58. File file1 = new File(rootDirectory, "file1.txt");
  59. File file2 = new File(rootDirectory, "file2.log");
  60. File file3 = new File(rootDirectory, "file3.csv");
  61. file1.writeText("This is file1 data.");
  62. file2.writeText("This is log data.");
  63. file3.writeText("This is csv data.");
  64. DirectoryDataFilter filter = new DirectoryDataFilter(rootDirectory, 3); // Retry 3 times
  65. List<String> data = filter.filterData();
  66. for (String item : data) {
  67. System.out.println(item);
  68. }
  69. }
  70. }

Add your comment