Java中如何用FileWriter将XML提取的数据保存到TXT文件?
Got it, let's fix that blank text file issue! The problem is you're currently only printing the extracted data to the console—you need to explicitly write that same content to your FileWriter, and make sure the writer is properly closed (or use try-with-resources to handle that automatically).
Here's your modified code that saves the results to a teacher_names.txt file (and still prints to the console):
package XMLConvertor; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Sample { public static void main(String argv[]) { try { // SourceFile File fXmlFile = new File("~/Downloads/Teacher.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); // Normalizing doc.getDocumentElement().normalize(); // Initialize FileWriter with try-with-resources (auto-closes the writer) try (FileWriter writer = new FileWriter("teacher_names.txt")) { String rootElementText = "Root element :" + doc.getDocumentElement().getNodeName() + "\n"; System.out.println(rootElementText); writer.write(rootElementText); String separator = "----------------------------\n"; System.out.println(separator); writer.write(separator); // Teacher name tags NodeList nList = doc.getElementsByTagName("TeacherName"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); String currentElementText = "\nCurrent Element :" + nNode.getNodeName() + "\n"; System.out.print(currentElementText); writer.write(currentElementText); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String nameText = "Name: " + eElement.getElementsByTagName("Name").item(0).getTextContent() + "\n"; System.out.print(nameText); writer.write(nameText); } } // Optional: Flush to ensure all content is written immediately writer.flush(); System.out.println("\nSuccessfully saved results to teacher_names.txt"); } catch (IOException e) { System.err.println("Error writing to file: " + e.getMessage()); e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } }
Key changes explained:
- Added
import java.io.FileWriter;andimport java.io.IOException;to handle file writing operations. - Used try-with-resources for the FileWriter: this automatically closes the writer when we're done, which is crucial—if you forget to close the writer, the content might never get flushed to the file (that's probably why your previous files were blank!).
- For every line you print to the console, we now write the exact same string to the FileWriter using
writer.write(). - Added a flush call (optional but good practice) to make sure all content is written to the file right away, instead of waiting for the buffer to fill.
- Added a success message so you know the file was saved correctly.
Now when you run this, you'll see the output in the console and a teacher_names.txt file in your project directory (or you can specify a full path like "/Users/yourname/Documents/teacher_names.txt" if you want it somewhere specific).
内容的提问来源于stack exchange,提问作者Sara Mirabi
相关产品推荐
相关产品推荐

