0

I m trying to create csv file from parsing xml data .When i m execute this code every-time data is append in to file not write data in new file or overwriting old file .

        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 ); 

generateCsvfile()

 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){

    }
}

How to overwrite the file?

Aanshi
  • 282
  • 1
  • 5
  • 22
  • unless you are doing this to learn the trade, there are third party libraries which lets you build CSV files. – Nishan Oct 17 '13 at 07:02

4 Answers4

1

According to the answer to this question the second argument to the FileWriter constructor is actually the flag that determines whether to append or overwrite.

Try changing your constructor statement from this

FileWriter writer = new FileWriter(sFilename,true);

to this

FileWriter writer = new FileWriter(sFilename);
Community
  • 1
  • 1
Igor Zinov'yev
  • 3,676
  • 1
  • 33
  • 49
1

You pass 'true' to the FileWriter constructor in generateCsvFile(). According to the Javadoc API if append is true, then bytes will be written to the end of the file rather than the beginning http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,boolean)

Oded Peer
  • 2,377
  • 18
  • 25
0

Beware of possible syntax errors, but the concept stay the same. Put this in your generateCsvFile just after the filewriter variable declaration.

if (sFilename.exists()) {
     try {
         sFilename.delete();
     }
     catch (IOException e) {
         e.printStackTrace();
         return;
     }
}

Basically, what you do is checking if the file exists, and try to delete it if it does. If the operation fails however, the whole method is canceled thus preventing the application to append the information to an existing file.

simme
  • 1,514
  • 12
  • 23
0

Your generateCsvFile() should look a bit like this :

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();           
                writer.append(mapEntry.getValue());
                writer.append(",");           
            }
            writer.append("\n");
        }
        writer.flush();
        writer.close();
    } catch(Exception e) {

    }
}
Igor Zinov'yev
  • 3,676
  • 1
  • 33
  • 49
Nishan
  • 2,821
  • 4
  • 27
  • 36