S
S
SpeakeazyYT22018-07-28 22:36:34
Java
SpeakeazyYT2, 2018-07-28 22:36:34

How to write the result of iteration in a for loop to a txt file?

Hello. I am writing a program in Java. In the code, I use a for loop to get values ​​from an xml file. Code below.

public static void main(String[] args) {
        try {
 
            // Строим объектную модель исходного XML файла
            final File xmlFile = new File(appdata, "file.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlFile);
 
            // Выполнять нормализацию не обязательно, но рекомендуется
            doc.getDocumentElement().normalize();
 
            // Получаем все узлы с именем "Server"
            NodeList nodeList = doc.getElementsByTagName("Server");
 
            for (int i = 0; i < nodeList.getLength(); i++) {
                // Выводим информацию по каждому из найденных элементов
                Node node = nodeList.item(i);
                if (Node.ELEMENT_NODE == node.getNodeType()) {
                    Element element = (Element) node;
                    String Host = element.getElementsByTagName("Host").item(0).getTextContent();
                }
            }
        } catch (ParserConfigurationException | SAXException
                | IOException ex) {
            Logger.getLogger(XMain.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }

The task is as follows: to get several values ​​​​from the xml file (it has been completed) and write them to a txt file, which must first be created. But since the display of the xml file values ​​is in the for loop and there can be many of these values, as a result of the loop sorting, only the last value is written. And if, for example, put System.out.println(Host); - then the loop will go through all the Host values ​​and return them in order.
How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
fOrZe0, 2018-07-28
@SpeakeazyYT2

PrintWriter printWriter = new PrintWriter(new File("f.txt")); // f.txt  ручками создавать не надо =)
for (int i = 0; i < 10; i++) {
     printWriter.write(i + "\n");
}
printWriter.close();

The file will be written
0
1
2
3
4
5
6
7
8
9

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question