2

In the Java code below, I am creating a *.html report by transforming generated xml data that is stored in a string,

combinedDDIString

... against an XSLT file,

reportXSLT

... and writing the result to a physical file,

tmpReportHTML.

The code then reads the file back into a string to use in other methods. I would like to avoid having to write the results to a file, just transform the results directly into a string.

Is there any way I can write the transform results to a string directly, and avoid writing the results out to a physical file?

    String reportString = null;
    FileInputStream stream = null;
    ByteArrayOutputStream reportBAOS = new ByteArrayOutputStream(); 

try {

    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer(new StreamSource(reportXSLT));
    transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    /*
     * Create a new report file time-stamped for uniqueness, to avoid concurrency issues
     */
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    Date date = new Date();
    File tmpReportHTML = new File(reportHTML + dateFormat.format(date) + ".html");

    /*
     * Perform the transform to get the report
     */
    FileOutputStream reportFOS = new FileOutputStream(tmpReportHTML);
    OutputStreamWriter osw = new OutputStreamWriter(reportFOS, "US-ASCII");//(reportBAOS), "US-ASCII");
    transformer.transform(new StreamSource(new StringReader(combinedDDIString)), new StreamResult(osw));
    osw.close();

    /*
     * Get the report as a string from the temp report file
     */
    //FileInputStream stream = new FileInputStream(new File(REPORT_OUTPUT)); 
    stream = new FileInputStream(tmpReportHTML); //(new File(reportXML));           
    FileChannel fc = stream.getChannel(); 
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); 
    reportString = Charset.defaultCharset().decode(bb).toString(); 

    /*
     * Delete the temp report file
     */
    tmpReportHTML.delete();


} catch (TransformerConfigurationException e) {
    e.printStackTrace();
} catch (Exception ex) {
    ex.printStackTrace();
}
finally { 
    stream.close(); 

Thanks in advance for the help.

Fuzzy Analysis
  • 3,168
  • 2
  • 42
  • 66

1 Answers1

5

Try using a StringWriter to create the StreamResult. (You should be able to obtain a String from the StringWriter simply using the toString method.)

rcgoncalves
  • 128
  • 6
  • 1
    Excellent, thank you. The related link to your answer is: http://stackoverflow.com/questions/13217657/how-to-convert-stream-results-to-string – Fuzzy Analysis Aug 01 '13 at 01:29