现在的位置: 首页 > 综合 > 正文

Velocity的中文问题

2013年10月23日 ⁄ 综合 ⁄ 共 1053字 ⁄ 字号 评论关闭

        今天做了一个小工具,通过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"));

        终于看到了久违的中文。

抱歉!评论已关闭.