1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. public class HtmlFormatter {
  5. public static void main(String[] args) {
  6. if (args.length != 1) {
  7. System.out.println("Usage: java HtmlFormatter <input_file>");
  8. return;
  9. }
  10. String inputFilePath = args[0];
  11. try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
  12. String line;
  13. while ((line = reader.readLine()) != null) {
  14. System.out.println(formatLine(line));
  15. }
  16. } catch (IOException e) {
  17. System.err.println("Error reading file: " + e.getMessage());
  18. }
  19. }
  20. private static String formatLine(String line) {
  21. // Basic indentation: indent after opening tags
  22. if (line.contains("<")) {
  23. int openTagIndex = line.indexOf("<");
  24. if (openTagIndex != -1) {
  25. // Find the closing tag
  26. int closingTagIndex = line.indexOf(">", openTagIndex);
  27. if (closingTagIndex != -1) {
  28. String openingTag = line.substring(0, openTagIndex + 1);
  29. String closingTag = line.substring(closingTagIndex);
  30. //Indentation level
  31. int indentationLevel = 0;
  32. while (openingTag.charAt(indentationLevel) != '{') {
  33. indentationLevel++;
  34. }
  35. String indentation = " ".repeat(indentationLevel);
  36. return indentation + line;
  37. } else {
  38. return line; // If closing tag not found, return as is
  39. }
  40. }
  41. }
  42. return line; // Return unchanged if no HTML tags
  43. }
  44. }

Add your comment