大量数据写入xml的方法

    技术2022-05-11  11

     package xml; import java.io.FileOutputStream; /** * 大量数据写人xml的方法 * @author jinchun * */ public class SaveXml { /** * @param args */ public static void main(String args[]) { try { saveToXML("d://temp.xml"); } catch (Exception e) { e.printStackTrace(); } } private synchronized static void saveToXML(String path) throws Exception{ FileOutputStream fos = new FileOutputStream(path, false); StringBuffer sb = new StringBuffer(); /** * 因为<?xml version="1.0" encoding="GBK"?>中包含""号。所以必须使用转义符 */ sb.append("<?xml version=/"1.0/" encoding=/"GBK/"?>"); /** * 切忌xml文件中顶层节点必须只有一个 */ sb.append("<root>"); for(int i = 0 ; i < 1000000; i++){ sb.append("<node>"); sb.append(i); sb.append("</node>"); if(i % 100 == 0){ fos.write(sb.toString().getBytes()); fos.flush(); fos.close(); fos = new FileOutputStream(path, true); sb = new StringBuffer(); } } sb.append("</root>"); System.out.println("完毕"); try{ fos.write(sb.toString().getBytes()); fos.flush(); fos.close(); }catch(Exception e){ } } }


    最新回复(0)