论坛首页 Java企业应用论坛

Freemarker输出字符串而不是文件

浏览 5601 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (3) :: 隐藏帖 (1)
作者 正文
   发表时间:2009-12-18   最后修改:2009-12-18

    Freemarker一般是通过writer输出到文件的处理过程,但是这个过程不是很优化的,大量的IO操作使程序变的很慢。尤其是生成对应的文件后,再做一些处理,更是慢上加慢。

    废话少说,先看看改造前的代码。

cfg.setClassForTemplateLoading(this.getClass(), "/");
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setNumberFormat("################");

Questionnaire questionnaire = questionnaireDAO.findById(input.getDialogId());
Map root = new HashMap();
root.put("questionnaire", questionnaire);

Template template = cfg.getTemplate("soapRequest.ftl");
OutputStream os = conn.getOutputStream();
Writer out = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));
template.process(root, out);
out.flush();
out.close();

 修改后的。

cfg.setClassForTemplateLoading(this.getClass(), "/");
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setNumberFormat("################");

Questionnaire questionnaire = questionnaireDAO.findById(input.getDialogId());
Map root = new HashMap();
root.put("questionnaire", questionnaire);
/**
* StringWriter instead of Writer
* Class StringWriter contains a StringBuffer which can be rendered toString
* modify by heweiya
*/
StringWriter stringWriter = new StringWriter();
BufferedWriter writer = new BufferedWriter(stringWriter);
template.setEncoding("UTF-8");
template.process(root, writer);
StringReader reader = new StringReader(stringWriter.toString());
writer.flush();
writer.close();

 说白了就是使用StringWriter代替了writer,我在代码里直接转换成了StringReader,同样,如果你没有必要做这个的话,你可以把StringWriter转换成String.

   发表时间:2009-12-23   最后修改:2009-12-23
BufferedWriter writer = new BufferedWriter(stringWriter);  
这一步不必要吧?
==================
		Configuration cfg = new Configuration();
		cfg.setDefaultEncoding(encoding);
		Template t = new Template(TEMPALTE_DEFAULT_KEY, new StringReader(
				templateStr), cfg);
		StringWriter out = new StringWriter();
		t.process(map, out);
		return out.getBuffer().toString();
0 请登录后投票
   发表时间:2009-12-25  
kiki 写道
BufferedWriter writer = new BufferedWriter(stringWriter);  
这一步不必要吧?
==================
		Configuration cfg = new Configuration();
		cfg.setDefaultEncoding(encoding);
		Template t = new Template(TEMPALTE_DEFAULT_KEY, new StringReader(
				templateStr), cfg);
		StringWriter out = new StringWriter();
		t.process(map, out);
		return out.getBuffer().toString();

雖然不必要但是有好處,用buffer對性能上好處多多。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics