Velocity的中文问题

来源:互联网 发布:免费喊单软件 编辑:程序博客网 时间:2024/06/06 10:02

http://blog.csdn.net/mydeman/article/details/6633242


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

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

[java] view plaincopyprint?
  1. public class VelocityHelper {  
  2.     private static VelocityContext vc;  
  3.       
  4.     static {  
  5.         vc = new VelocityContext();  
  6.     }  
  7.   
  8.     public static void generateFile(String tempatePath, String destPath, Map<String, Object> attributes){  
  9.         Template template = Velocity.getTemplate(tempatePath);  
  10.           
  11.         for(String key : attributes.keySet()){  
  12.             vc.put(key, attributes.get(key));  
  13.         }  
  14.           
  15.         BufferedWriter bw = null;  
  16.         try {  
  17.             bw = new BufferedWriter(new FileWriter(destPath));  
  18.               
  19.             template.merge(vc, bw);  
  20.               
  21.             bw.flush();  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         } finally {  
  25.             if(bw != null){  
  26.                 try {  
  27.                     bw.close();  
  28.                 } catch (IOException e) {  
  29.                 }  
  30.             }  
  31.         }  
  32.     }  
  33. }  

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

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

[java] view plaincopyprint?
  1. Template template = Velocity.getTemplate(tempatePath, "UTF-8");  

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

[java] view plaincopyprint?
  1. //template.merge(vc, bw);  
  2. Velocity.mergeTemplate(destPath, "UTF-8", vc, bw);  

        可是这两种方法并不起作用。正在偶然之间看到了上面初始BufferedWriter的代码,这才是生成文件的关键代码,将其修改为:

[java] view plaincopyprint?
  1. bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destPath), "UTF-8"));  

        终于看到了久违的中文。
0 0