1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. public class HtmlMerger {
  7. public static void mergeHtmls(List<String> htmlFiles, String outputHtmlFile) throws IOException {
  8. // Create a map to store unique HTML snippets, indexed by a simple hash.
  9. Map<String, String> htmlCache = new HashMap<>();
  10. try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputHtmlFile))) {
  11. for (String htmlFile : htmlFiles) {
  12. try (BufferedReader reader = new BufferedReader(new FileReader(htmlFile))) {
  13. String htmlContent = reader.readAllText();
  14. // Generate a unique hash for the HTML content. Simple hash for demo.
  15. String htmlHash = generateHash(htmlContent);
  16. // Check if the HTML content is already in the cache.
  17. if (htmlCache.containsKey(htmlHash)) {
  18. // Reuse the cached HTML content.
  19. writer.write(htmlCache.get(htmlHash));
  20. } else {
  21. // Add the HTML content to the cache.
  22. htmlCache.put(htmlHash, htmlContent);
  23. writer.write(htmlContent);
  24. }
  25. }
  26. }
  27. }
  28. }
  29. // Simple hash function for HTML content. Can be improved for better distribution.
  30. private static String generateHash(String html) {
  31. return String.valueOf(html.hashCode());
  32. }
  33. public static void main(String[] args) throws IOException {
  34. // Example usage:
  35. List<String> htmlFiles = new ArrayList<>();
  36. htmlFiles.add("file1.html");
  37. htmlFiles.add("file2.html");
  38. htmlFiles.add("file3.html");
  39. mergeHtmls(htmlFiles, "merged.html");
  40. }
  41. }

Add your comment