作者:渐我素小黑陈琼敏 | 来源:互联网 | 2023-06-03 10:24
官方文档: http:ibeetl.comguide#beetl多谢beetl的作者抽空指点!!!根据远程文件服务器生成模板:需要注意的是:StringTemplateResour
官方文档: http://ibeetl.com/guide/#beetl
多谢beetl的作者抽空指点!!!
根据远程文件服务器生成模板:
需要注意的是:
- StringTemplateResourceLoader:字符串模板加载器,用于加载字符串模板,如本例所示(根据url读取文件内容,然后根据这个对象生成Template对象)
- FileResourceLoader:文件模板加载器,需要一个根目录作为参数构造,传入getTemplate方法的String是模板文件相对于Root目录的相对路径
- ClasspathResourceLoader:文件模板加载器,模板文件位于Classpath里
- WebAppResourceLoader:用于webapp集成,假定模板根目录就是WebRoot目录,参考web集成章
- MapResourceLoader : 可以动态存入模板
- CompositeResourceLoader 混合使用多种加载方式
protected void generateFile(String template, String filePath) {
if(template.indexOf("http") != -1) {
try {
//创建一个URL实例
URL url = new URL("http://xxx/xxx/wKgUFFub3CmAer4pAAABjPGvkcI576.btl");
//通过URL的openStrean方法获取URL对象所表示的自愿字节输入流
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is,"utf-8");
//为字符输入流添加缓冲
BufferedReader br = new BufferedReader(isr);
String data = null;//读取数据
StringBuffer sb = new StringBuffer();
while ((data = br.readLine())!=null){//循环读取数据
data += "\r\n";
sb.append(data);
}
br.close();
isr.close();
is.close();
StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
Configuration cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate(resourceLoader,cfg);
Template pageTemplate = gt.getTemplate(sb.toString());
templateToFile(filePath, pageTemplate);
} catch (IOException e) {
e.printStackTrace();
}
}else {
Template pageTemplate = groupTemplate.getTemplate(template);
templateToFile(filePath, pageTemplate);
}
}
protected void templateToFile(String filePath, Template pageTemplate) {
configTemplate(pageTemplate);
if (PlatformUtil.isWindows()) {
filePath = filePath.replaceAll("/+|\\\\+", "\\\\");
} else {
filePath = filePath.replaceAll("/+|\\\\+", "/");
}
File file = new File(filePath);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
pageTemplate.renderTo(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}