场景描述:
最近写一个博客系由于需要批量生成网页,所以写这么一个小功能
直接上代码了
html模板(根据需要自己随便写,这这是个测试)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#title#</title>
<style>
body{ text-align:center;border: 0px;margin: 0px;background-color: #F4F4F4;}
.div{ margin:0 auto; width:1188px; height:auto;}
</style>
</head>
<body>
<div class="div">
<div>
#div#
</div>
</div>
</body>
</html>
java代码
package html;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* @ClassName: CreateHtmlUtils
* @Description: Java 根据模板创建 html
* @author
* @date 2016年4月22日 下午3:51:16
*/
public class CreateHtmlUtils {
public static void main(String[] args) {
String filePath = "f:/testHtml/test.html";
String imagePath ="f:/test.png";
String disrPath = "f:/newHtml/test/";
String fileName = String.valueOf(System.currentTimeMillis());
MakeHtml("我是抬头",filePath,imagePath,disrPath,fileName);
}
/**
* @Description: 创建html
* @param title 设定模板title
* @param filePath 设定模板文件
* @param imagePath 需要显示图片的路径
* @param disrPath 生成html的存放路径
* @param fileName 生成html名字
* @return void 返回类型
* @throws
*/
public static void MakeHtml(String title,String filePath,String imagePath,String disrPath,String fileName ){
try {
String div = "<image src="+'"'+imagePath+'"'+"/>";
String templateContent = "";
FileInputStream fileinputstream = new FileInputStream(filePath);
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
templateContent = new String(bytes);
System.out.print(templateContent);
templateContent = templateContent.replaceAll("#title#", title);
templateContent = templateContent.replaceAll("#div#", div);
String fileame = fileName + ".html";
fileame = disrPath+"/" + fileame;
FileOutputStream fileoutputstream = new FileOutputStream(fileame);
byte tag_bytes[] = templateContent.getBytes();
fileoutputstream.write(tag_bytes);
fileoutputstream.close();
} catch (Exception e) {
System.out.print(e.toString());
}
}
}