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功能就實現了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章