我正在尝试通过解析 xml 数据创建 csv 文件。当我执行此代码时,每次数据都附加到文件中,而不是在新文件中写入数据或覆盖旧文件。
File fXmlFile = new File("d:/formdata.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("record");
System.out.println("----------------------------");
List< Map<String, String>> list = new ArrayList<Map<String,String>>();
for (int temp = 0; temp < nList.getLength(); temp++) {
Map<String, String> map = new HashMap<String, String>();
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
map.put("Item No", eElement.getElementsByTagName("item_no").item(0).getTextContent());
map.put("Description", eElement.getElementsByTagName("description").item(0).getTextContent());
map.put("price", eElement.getElementsByTagName("price").item(0).getTextContent());
map.put("base qty", eElement.getElementsByTagName("base_qty").item(0).getTextContent());
map.put("Var qty", eElement.getElementsByTagName("var_qty").item(0).getTextContent());
list.add(map);
}
}
generateCsvFile("E:\\testCSV.csv", list );
生成Csvfile()
private static void generateCsvFile(String sFilename, List< Map<String, String>> test) {
try {
FileWriter writer = new FileWriter(sFilename,true);
for (Map<String, String> map : test) {
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> mapEntry = (Map.Entry<String,String>) iterator.next();
//ystem.out.println("key: " + mapEntry.getKey() + ", value:" + mapEntry.getValue());
writer.append(mapEntry.getValue());
writer.append(",");
iterator.remove();
}
}
writer.flush();
writer.close();
}catch(Exception e){
}
}
如何覆盖文件?