Velocity的中文问题

今天做了一个小工具,通过Velocity生成Latext的tex文件,可是当使用Miktex生成PDF时,里面的中文都变成了乱码。而之前在Eclipse直接运行时,并没有发现问题。毫无疑问是文件编码引起的问题。

用Notepad++打开生成的tex文件,发现文件的编码是ANSI,也就是系统本地的编码。下面是生成tex的代码:

public class VelocityHelper { private static VelocityContext vc; static { vc = new VelocityContext(); } public static void generateFile(String tempatePath, String destPath, Map<String, Object> attributes){ Template template = Velocity.getTemplate(tempatePath); for(String key : attributes.keySet()){ vc.put(key, attributes.get(key)); } BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(destPath)); template.merge(vc, bw); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if(bw != null){ try { bw.close(); } catch (IOException e) { } } } } }

Google了一下找到了两种解决乱码问题的方法:

1. 在获取模板文件时指定编码,即:

Template template = Velocity.getTemplate(tempatePath, "UTF-8");

2. 在生成文件时指定编码,即:

//template.merge(vc, bw); Velocity.mergeTemplate(destPath, "UTF-8", vc, bw);
可是这两种方法并不起作用。正在偶然之间看到了上面初始BufferedWriter的代码,这才是生成文件的关键代码,将其修改为:

bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destPath), "UTF-8"));
终于看到了久违的中文。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值