Please enable / Bitte aktiviere JavaScript!
Veuillez activer / Por favor activa el Javascript![ ? ]
How to write to txt file the result of iterating in a for loop? - Q&A

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

0 like 0 dislike
Hello. Write a program in Java. In the code use a for loop for getting values from an xml file. Code below.
public static void main(String[] args) { try { // Build the object model of the source XML file final File xmlFile = new File(appdata, "file.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(xmlFile); // Run normalization is not required, but recommended doc.getDocumentElement().normalize(); // Get all nodes with name 'Server' NodeList nodeList = doc.getElementsByTagName("Server"); for (int i = 0; i < nodeList.getLength(); i++) { // Print information on each of the found elements 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 challenge is to get from xml file with multiple values (it is made) and write them to a txt file, which must first be created. But as the display values from the xml file to be in the loop and these values may be many, the result of the re-cycle, record only the latest. And if for example the supply System.out.println(Host); - the loop will iterate all the values of the Host and will issue the order.
How to do it?
asked by | 11 views

1 Answer

0 like 0 dislike
PrintWriter printWriter = new PrintWriter(new File("f.txt")); // f.txt handles no need to create =) for (int i = 0; i < 10; i++) { printWriter.write(i + "\"); } printWriter.close();

The file will be written
0 1 2 3 4 5 6 7 8 9
answered by
Welcome to Bug-code Q&A, where you can ask questions and receive answers from other members of the community.

24.8k questions

46.2k answers


13.3k users

24,788 questions
46,220 answers
13,321 users