You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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; and import 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:17:52