根据模板生成HTML文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LONG729564606/article/details/80468813

场景描述:

最近写一个博客系由于需要批量生成网页,所以写这么一个小功能

直接上代码了

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+'"'+"/>";
//            System.out.print(filePath);
            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;// 生成的html文件保存路径。
            FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件输出流
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }


}

猜你喜欢

转载自blog.csdn.net/LONG729564606/article/details/80468813
今日推荐