Home > Backend Development > PHP Tutorial > velocity application example 10---output to file

velocity application example 10---output to file

黄舟
Release: 2023-03-04 21:40:01
Original
1386 people have browsed it

velocity第10个应用例子---输出到文件

//2 Create a Context object

VelocityContext context = newVelocityContext();

//3 Add you data object to this context

context.put("title", "银联电子");

context.put("body", "这是内容"); 

//4 Choose a template

Template template =Velocity.getTemplate("file.vm");

//创建文件

File saveFile = newFile("G:\\workspace\\zjq\\velocity\\WebRoot\\page\\test.html");

//获得它的父类文件,如果不存在,就创建

if(!saveFile.getParentFile().exists()) {


saveFile.getParentFile().mkdirs();

}

//创建文件输出流

FileOutputStream outStream = newFileOutputStream(saveFile);

//因为模板整合的时候,需要提供一个Writer,所以创建一个Writer

OutputStreamWriter writer = newOutputStreamWriter(outStream);

//创建一个缓冲流

BufferedWriter bufferWriter = newBufferedWriter(writer);



//5 Merge the template and you data toproduce the output

template.merge(context, bufferWriter);

bufferWriter.flush();//强制刷新

outStream.close();

bufferWriter.close();
Copy after login

file.vm

<!DOCTYPE
html>

<html>

<head>

<meta
charset="UTF-8">

<title>$title</title>

</head>

<body>

$body

</body>

</html>
Copy after login

以上就是velocity,输出到文件的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template