0

I have the following code to transform the xml file to html file.This is accessed by many threads.The transform method just appends the content every time.That is the first threads content is retained in all subsequent thread's html files.

public class CreateHTML
{
    TransformerFactory tFactory;
    Source xslDoc;
    Source xmlDoc;
    OutputStream htmlFile;
    public CreateHTML(String xslDocFileName,String xmlDocFileName,String outputFileName) throws FileNotFoundException
    {
        xslDoc=new StreamSource(xslDocFileName);
        xmlDoc=new StreamSource(xmlDocFileName);
        htmlFile=new FileOutputStream(outputFileName);
    }
    public synchronized void createOutputFile() throws Exception
    {
        try
        {
            tFactory=TransformerFactory.newInstance();
            tFactory.setAttribute("indent-number",new Integer(2));
            Transformer transformer = tFactory.newTransformer(xslDoc);
            transformer.setOutputProperty(OutputKeys.INDENT,"yes");
            transformer.transform(xmlDoc, new StreamResult(htmlFile));
        }
        catch (TransformerException ex)
        {
            Logger.getLogger(CreateHTML.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }
    }
}
Siva Hari
  • 1
  • 1
  • 6
  • Your Problem is not synchronization. The class actually behaves as expected from what the code sais. You don't close the OutputStream in between calls to createOutputFile, so it is appended to. – Fildor Aug 13 '14 at 07:04
  • I tried closing OutputStream.It doesnot work. – Siva Hari Aug 13 '14 at 07:17
  • How are you accessing the createOutputFile method? How are you creating your threads and instantiating CreateHTML? – Chan Aug 13 '14 at 09:22
  • Its a web app so thread creation is done by jsp itself.And im simply creating an object for CreateHTML for calling the createOutputFile method.. – Siva Hari Aug 13 '14 at 10:17
  • Possible duplicate of [Threads and file writing](http://stackoverflow.com/questions/9972549/threads-and-file-writing) – Vadzim Oct 16 '15 at 15:47

0 Answers0