http://blog.youkuaiyun.com/mydeman/article/details/6633242
今天做了一个小工具,通过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"));
终于看到了久违的中文。

本文详细阐述了使用Velocity生成Latext文件过程中遇到的中文乱码问题,以及通过修改文件生成关键代码解决该问题的过程。重点介绍了在获取模板文件和生成文件时指定编码的方法,最终通过正确设置OutputStreamWriter参数成功解决了乱码问题。
1969

被折叠的 条评论
为什么被折叠?



