Java根据html模板创建 html文件

时间:2019-08-30
本文章向大家介绍Java根据html模板创建 html文件,主要包括Java根据html模板创建 html文件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.创建html的java代码

package com.tydic.eshop.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;

/**
 * @ClassName: CreateHtmlUtils  
 * @Description: Java 根据模板创建 html
 * @author 
 * @date 2016年4月22日 下午3:51:16
 */
public class CreateHtmlUtils {
    
    public static void main(String[] args) {
        String filePath = "E:\\hh_web_space\\ecp\\web\\ecp_web_page\\src\\main\\webapp\\template\\template.html";
        String imagePath ="http://localhost:8080/ecp/upload/1461293787628/1461293787628.jpg";
        String disrPath = "E:\\hh_web_space\\ecp\\web\\ecp_web_page\\src\\main\\webapp\\template\\";
        String fileName = "liuren";
        MakeHtml(filePath,imagePath,disrPath,fileName);
    }
    /**
     * @Title: MakeHtml 
     * @Description: 创建html
     * @param    filePath 设定模板文件
     * @param    imagePath 需要显示图片的路径
     * @param    disrPath  生成html的存放路径
     * @param    fileName  生成html名字 
     * @return void    返回类型 
     * @throws
     */
    public static void MakeHtml(String filePath,String imagePath,String disrPath,String fileName ){
        try {
            String title = "<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);
            System.out.print(templateContent);
            
            String fileame = fileName + ".html";
            fileame = disrPath+"/" + fileame;// 生成的html文件保存路径。
            FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件输出流
            System.out.print("文件输出路径:");
            System.out.print(fileame);
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
    
    
}

2.然后是html的模板template.html,根据此模板生成的新的html文件

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<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>
        ###title###
    </div> 
</div> 
</body> 
</html> 

3.java代码会常见新的html文件,并替换掉 ###title### 为图片的标签。

然后可以生成静态网页了。效果图如下:

一个简单的java生成html功能就实现了。

原文地址:https://www.cnblogs.com/zhuyeshen/p/11435582.html