package org.unique.generator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

/**
 * 模板操作类
 * @ClassName: CodeGenerator
 * @author AndrewWen
 * @date 2013-1-14 下午5:25:30
 */
public class VelocityInfoOp {

	public static void generatorCode(String templateFile, Map<String, Object> contextMap, String path, String fileName) {
		//设置模板载入路径
		VelocityContext context = new VelocityContext();

		//获取模板引擎
		VelocityEngine ve = new VelocityEngine();

		//模板文件所在的路径
		String vPath = System.getProperty("user.dir") + "\\template";

		//设置参数
		ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, vPath);

		//处理中文问题
		ve.setProperty(Velocity.INPUT_ENCODING, "UTF-8");

		ve.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");

		//初始化模板
		ve.init();

		//设置变量值
		for (Object key : contextMap.keySet()) {
			context.put(key.toString(), contextMap.get(key));
		}

		Template template = null;

		try {
			template = ve.getTemplate(templateFile);
		} catch (Exception e) {
			e.printStackTrace();
		}

		StringWriter sw = new StringWriter();

		if (template != null){
			template.merge(context, sw);
		}

		//生成目录
		File pathTemp = new File(path);
		if (!pathTemp.exists()) {
			pathTemp.mkdirs();
		}

		/**
		 * 文件写入流
		 */
		writeFile(pathTemp + "/" + fileName, sw.toString());
	}

	/**
	 * 写入文件
	 * @Title: writeFile 
	 * @param filePathAndName
	 * @param fileContent
	 */
	public static void writeFile(String filePathAndName, String fileContent) {
		try {
			File f = new File(filePathAndName);
			if (!f.exists()) {
				f.createNewFile();
			}
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(fileContent);
			writer.close();
		} catch (Exception e) {
			System.out.println("写文件内容操作出错");
			e.printStackTrace();
		}
	}

}
最近下载更多
978806986  LV16 2022年3月25日
675104182  LV14 2020年9月22日
Zhangshuzi  LV1 2020年6月25日
wei112233  LV15 2020年5月11日
mingpl  LV9 2020年2月16日
a243933863  LV1 2019年11月25日
werwrer  LV6 2019年11月4日
1165166678  LV1 2019年10月8日
648020894  LV1 2019年7月9日
398163660sj  LV1 2019年6月27日
最近浏览更多
微信网友_6234675614470144  LV1 2024年10月28日
sswert  LV2 2024年9月12日
3334004690  LV10 2024年6月24日
hellolu21  LV10 2024年5月16日
泓鼎168  LV20 2024年3月6日
漫步的海星  LV4 2023年9月25日
guviva  LV6 2023年6月12日
zzuljh  LV9 2023年4月25日
taoshen95  LV16 2023年4月13日
痴汉hug个人民 2023年2月21日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友