1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.ScheduledExecutorService;
  6. import java.util.concurrent.TimeUnit;
  7. public class FileContentMonitor {
  8. private final String filePath;
  9. private String previousContent = null;
  10. private final int checkIntervalSeconds;
  11. public FileContentMonitor(String filePath, int checkIntervalSeconds) {
  12. this.filePath = filePath;
  13. this.checkIntervalSeconds = checkIntervalSeconds;
  14. }
  15. public void startMonitoring() {
  16. ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  17. scheduler.scheduleAtFixedRate(this::checkFileContent, 0, checkIntervalSeconds, TimeUnit.SECONDS);
  18. }
  19. private void checkFileContent() {
  20. try {
  21. String currentContent = readWholeFile(filePath);
  22. if (currentContent != null && !currentContent.equals(previousContent)) {
  23. System.out.println("File content changed: " + currentContent);
  24. previousContent = currentContent;
  25. }
  26. } catch (IOException e) {
  27. System.err.println("Error reading file: " + e.getMessage());
  28. // Handle potential errors, e.g., file not found, permission issues
  29. // Consider logging the error.
  30. }
  31. }
  32. private String readWholeFile(String filePath) throws IOException {
  33. BufferedReader reader = null;
  34. StringBuilder sb = new StringBuilder();
  35. try {
  36. reader = new BufferedReader(new FileReader(filePath));
  37. String line;
  38. while ((line = reader.readLine()) != null) {
  39. sb.append(line).append(System.lineSeparator()); // Preserve line breaks
  40. }
  41. } finally {
  42. if (reader != null) {
  43. try {
  44. reader.close();
  45. } catch (IOException e) {
  46. System.err.println("Error closing file reader: " + e.getMessage());
  47. }
  48. }
  49. }
  50. return sb.toString();
  51. }
  52. public static void main(String[] args) {
  53. // Example Usage:
  54. String filePath = "test.txt"; // Replace with your file path
  55. int checkInterval = 5; // Check every 5 seconds
  56. // Create a dummy file for testing
  57. try {
  58. java.io.FileWriter fw = new java.io.FileWriter(filePath);
  59. fw.write("Initial content.\n");
  60. fw.close();
  61. } catch (IOException e) {
  62. System.err.println("Error creating test file: " + e.getMessage());
  63. return;
  64. }
  65. FileContentMonitor monitor = new FileContentMonitor(filePath, checkInterval);
  66. monitor.startMonitoring();
  67. // Keep the main thread alive to allow monitoring to continue
  68. try {
  69. Thread.sleep(60000); // Run for 60 seconds
  70. } catch (InterruptedException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. }

Add your comment