Here is my code using stack
package com.codegym.task.task19.task1918;

/*
Introducing tags

*/

import java.io.*;
import java.util.*;

public class Solution {
    public static void main(String[] args) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String filename = reader.readLine();
        reader.close();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        FileReader fr = new FileReader(filename);
        while (fr.ready()) {
            os.write((char) fr.read());
        }
        fr.close();
        String str = os.toString();

        String openingTag = "<" + args[0];
        String closingTag = "</" + args[0] + ">";

        Map<Integer, String> treeMap = new TreeMap<>();

        Stack<Integer> stack = new Stack<>();
        int index = 0;
        while (index < str.length()) {
            if (str.substring(index).startsWith(openingTag)) {
                stack.push(index);
                index += openingTag.length();
            } else if (str.substring(index).startsWith(closingTag)) {
                int startIndex = stack.pop();
                treeMap.put(startIndex, str.substring(startIndex, index + closingTag.length()));
                index += closingTag.length();
            } else {
                index++;
            }
        }

        for (Map.Entry<Integer, String> entry : treeMap.entrySet())
            System.out.println(entry.getValue());
    }
}