1. import javax.swing.*;
  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.Timer;
  6. import java.util.TimerTask;
  7. public class HtmlWatcher {
  8. private String htmlFilePath;
  9. private String previousContent = "";
  10. private JFrame frame;
  11. private JTextArea textArea;
  12. public HtmlWatcher(String htmlFilePath) {
  13. this.htmlFilePath = htmlFilePath;
  14. // Create GUI
  15. frame = new JFrame("HTML Watcher");
  16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  17. frame.setSize(800, 600);
  18. textArea = new JTextArea();
  19. textArea.setEditable(false);
  20. JScrollPane scrollPane = new JScrollPane(textArea);
  21. frame.add(scrollPane);
  22. frame.setVisible(true);
  23. // Start watching
  24. Timer timer = new Timer();
  25. timer.scheduleAtFixedRate(new WatchTask(), 0, 1000); // Check every 1 second
  26. }
  27. private class WatchTask extends TimerTask {
  28. @Override
  29. public void run() {
  30. try {
  31. String currentContent = readHtmlFile();
  32. if (!currentContent.equals(previousContent)) {
  33. textArea.setText(currentContent);
  34. previousContent = currentContent;
  35. System.out.println("HTML file changed."); // Simple error message
  36. }
  37. } catch (IOException e) {
  38. textArea.setText("Error reading HTML file: " + e.getMessage());
  39. System.err.println("Error reading HTML file: " + e.getMessage());
  40. }
  41. }
  42. }
  43. private String readHtmlFile() throws IOException {
  44. try (BufferedReader reader = new BufferedReader(new FileReader(htmlFilePath))) {
  45. StringBuilder content = new StringBuilder();
  46. String line;
  47. while ((line = reader.readLine()) != null) {
  48. content.append(line).append("\n");
  49. }
  50. return content.toString();
  51. }
  52. }
  53. public static void main(String[] args) {
  54. // Replace with your HTML file path
  55. String htmlFilePath = "example.html";
  56. SwingUtilities.invokeLater(() -> new HtmlWatcher(htmlFilePath));
  57. }
  58. }

Add your comment