以UTF-8强制写入Velocity文件

时间:2013-06-14 13:48:34

标签: java encoding utf-8 velocity

我正在使用以下代码将Velocity模板输出到文件:

FileWriter fileWriterOut = new FileWriter(outFile);
logger.debug("encoding " + fileWriterOut.getEncoding());
fileWriterOut.write(template.getStringWriter().toString());
fileWriterOut.close();

问题是:

部署在非UTF-8应用服务器中,outFile使用默认编码(iso-xxxx)编写。

您可以使用fileWriterOut.getEncoding()

进行验证

似乎FileWriter类中的任何方法都无法设置其他编码。

如何在编写文件时强制使用UTF-8?

2 个答案:

答案 0 :(得分:3)

FileOutputStreamOutputStreamWriter

结合使用
final OutputStream out = new FileOutputStream(...);
final Writer writer 
    = new OutputStreamWriter(out, Charset.forName("UTF-8"));

答案 1 :(得分:0)

我找到了这样做的方法,我不确定这是最方便的方法,但它可以正常工作。

Writer out = null;
try {
    out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
    out.write(template.getStringWriter().toString());
} 
catch ...
finally
{
    try {
        out.close();
    } catch...
}