如何在java中将大字符串保存到xml文件中?

时间:2012-02-27 18:29:49

标签: java xml

我将一些大数据作为xml格式加载到我程序中的一个字符串中(来自mysql),当我将这个字符串保存到out.xml中时,只存储了大约500条记录。 如何将大型字符串或其他数据以xml格式或任何其他格式保存到文件中?

这是我的代码:

    String xmlString = doExportIntoString();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    InputSource source = new InputSource(new StringReader(xmlString));
    Document document =factory.newDocumentBuilder().parse(source);        
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    Result result = new StreamResult(new File("C:\\xmlFile.xml"));
    Source s = new DOMSource(document);
    transformer.transform(s, result);

2 个答案:

答案 0 :(得分:2)

以上是上述代码的正确版本:

BufferedWriter out;
try {
    out = new BufferedWriter(new FileWriter("out.txt"));
    out.write("aString");
} catch (IOException e) {
    throw new RuntimeException(e);    
} finally {
    if (out != null) {
        try { out.close(); } catch (IOException e) {}
    }
}

答案 1 :(得分:0)

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
    out.write("aString");
    out.close();
} catch (IOException e) {
}