Wednesday, January 01, 2014

Problem with Groovy Writer

In the following code

package com.tcs.ngps.htmlparsers

import org.jsoup.Jsoup
import org.jsoup.nodes.Document

class JSoupParser {

    public JSoupParser() {

    }

    static main(args) {
        String lString = (new File(args[0])).getText()
        Document lDocument = Jsoup.parse(lString)
        lDocument.outputSettings().prettyPrint(true);
        //(new File("D:/Temp/AWRJSoupParsed.html")).newWriter().write(lDocument.toString())
        def lBufferedWriter = new BufferedWriter(new FileWriter(new File("D:/Temp/AWRJSoupParsed.html")))
        lBufferedWriter.write(lDocument.toString())
        lBufferedWriter.close()
    }
}
The above code reads an HTML file and converts it to a XML file using JSoup parser. It then writes the XML to a file.
Now if the code 
(new File("D:/Temp/AWRJSoupParsed.html")).newWriter().write(lDocument.toString())
is used to write the file to the output the output file is always smaller than the total length of the string (when the String is large). Only when one uses the following code
def lBufferedWriter = new BufferedWriter(new FileWriter(new File("D:/Temp/AWRJSoupParsed.html")))
lBufferedWriter.write(lDocument.toString())
lBufferedWriter.close()

Is the whole file written. Unable to figure out why.

No comments: