2

在下面的 Java 代码中,我通过转换存储在字符串中的生成的 xml 数据来创建一个 *.html 报告,

combinedDDIString

...针对 XSLT 文件,

reportXSLT

...并将结果写入物理文件,

tmpReportHTML.

然后代码将文件读回字符串以在其他方法中使用。我想避免将结果写入文件,只需将结果直接转换为字符串即可。

有什么办法可以直接将转换结果写入字符串,并避免将结果写入物理文件?

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

在此先感谢您的帮助。

4

1 回答 1

4

尝试使用 aStringWriter创建StreamResult. (您应该能够StringStringWriter简单地使用该toString方法获得 a 。)

于 2013-07-31T23:49:49.533 回答