Problem with FileWriter into multiple files in Java

By : Amin
Source: Stackoverflow.com
Question!

I'm using java with freemarker to generate HTML files through the FTL (the template file) and XML. I got the result in multiple files but each file contains the whole result. I want each file to contain its own result. To give you more details, take a look at this part of my java code: (the solution should be so easy but I can't find it)

static void freemarkerDo(Map datamodel, String template) throws Exception{
  try {
      File file = new File("Avis.xml");
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(file);
      doc.getDocumentElement().normalize();
      NodeList nodeLst = doc.getElementsByTagName("Avis");

      Configuration cfg = new Configuration();

      Template tpl = cfg.getTemplate(template);



      for (int s = 0; s < nodeLst.getLength(); s++) {

        Node fstNode = nodeLst.item(s);

        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

            Element fstElmnt = (Element) fstNode;
            NodeList flNmElmntLst = fstElmnt.getElementsByTagName("Filename");
            Element flNmElmnt = (Element) flNmElmntLst.item(0);
            NodeList flNm = flNmElmnt.getChildNodes();
            FileWriter writer = new FileWriter(((Node) flNm.item(0)).getNodeValue()+".html");

            try {
                tpl.process(datamodel, writer);
                }
            finally{
                writer.close();
                    }
                                                        }



      }
      } catch (Exception e) {
        e.printStackTrace();
      }

}

Thanks for your help.

By : Amin


Answers

I don't know what this method does or where datamodel is set, however it would appear to me that you are passing the entire datamodel, so that would explain why you have the entire datamodel in each file.

tpl.process(datamodel, writer); // does what, with what?

What do you see when you debug your code?



This video can help you solving your question :)
By: admin