import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class DirectoryDataFilter {
private final File rootDir;
private final int maxRetries;
private final AtomicInteger retryCount = new AtomicInteger(0);
public DirectoryDataFilter(File rootDir, int maxRetries) {
this.rootDir = rootDir;
this.maxRetries = maxRetries;
}
public List<String> filterData() throws IOException {
List<String> filteredData = new ArrayList<>();
File[] files = rootDir.listFiles();
if (files != null) {
for (File file : files) {
try {
String data = processFile(file); // Process each file
if (data != null && !data.isEmpty()) {
filteredData.add(file.getAbsolutePath() + ": " + data);
}
} catch (IOException e) {
if (retryCount.get() < maxRetries) {
retryCount.incrementAndGet();
try {
System.err.println("Retry processing " + file.getName() + " (attempt " + retryCount.get() + ")");
processFile(file); // Retry processing
} catch (IOException retryException) {
System.err.println("Failed to process " + file.getName() + " after " + maxRetries + " retries.");
// Handle failure - e.g., log, skip, or throw an exception
}
} else {
System.err.println("Failed to process " + file.getName() + " after " + maxRetries + " retries.");
// Handle failure - e.g., log, skip, or throw an exception
}
}
}
}
return filteredData;
}
private String processFile(File file) throws IOException {
// Simulate data processing - replace with your actual logic
if (file.getName().endsWith(".txt")) {
return "Data from " + file.getName();
} else if (file.getName().endsWith(".log")) {
return "Log data from " + file.getName();
} else {
return null; // Return null if file type is not supported
}
}
public static void main(String[] args) throws IOException {
// Example usage:
File rootDirectory = new File("test_dir"); // Replace with your directory
File[] files = new File[] { rootDirectory, rootDirectory.mkdir() };
// Create some dummy files
File file1 = new File(rootDirectory, "file1.txt");
File file2 = new File(rootDirectory, "file2.log");
File file3 = new File(rootDirectory, "file3.csv");
file1.writeText("This is file1 data.");
file2.writeText("This is log data.");
file3.writeText("This is csv data.");
DirectoryDataFilter filter = new DirectoryDataFilter(rootDirectory, 3); // Retry 3 times
List<String> data = filter.filterData();
for (String item : data) {
System.out.println(item);
}
}
}
Add your comment