import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class FileContentMonitor {
private final String filePath;
private String previousContent = null;
private final int checkIntervalSeconds;
public FileContentMonitor(String filePath, int checkIntervalSeconds) {
this.filePath = filePath;
this.checkIntervalSeconds = checkIntervalSeconds;
}
public void startMonitoring() {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(this::checkFileContent, 0, checkIntervalSeconds, TimeUnit.SECONDS);
}
private void checkFileContent() {
try {
String currentContent = readWholeFile(filePath);
if (currentContent != null && !currentContent.equals(previousContent)) {
System.out.println("File content changed: " + currentContent);
previousContent = currentContent;
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
// Handle potential errors, e.g., file not found, permission issues
// Consider logging the error.
}
}
private String readWholeFile(String filePath) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append(System.lineSeparator()); // Preserve line breaks
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Error closing file reader: " + e.getMessage());
}
}
}
return sb.toString();
}
public static void main(String[] args) {
// Example Usage:
String filePath = "test.txt"; // Replace with your file path
int checkInterval = 5; // Check every 5 seconds
// Create a dummy file for testing
try {
java.io.FileWriter fw = new java.io.FileWriter(filePath);
fw.write("Initial content.\n");
fw.close();
} catch (IOException e) {
System.err.println("Error creating test file: " + e.getMessage());
return;
}
FileContentMonitor monitor = new FileContentMonitor(filePath, checkInterval);
monitor.startMonitoring();
// Keep the main thread alive to allow monitoring to continue
try {
Thread.sleep(60000); // Run for 60 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Add your comment