Write HTML file using Java

前端 未结 10 920
我寻月下人不归
我寻月下人不归 2020-11-28 23:55

I want my Java application to write HTML code in a file. Right now, I am hard coding HTML tags using java.io.BufferedWriter class. For Example:

BufferedWrite         


        
10条回答
  •  死守一世寂寞
    2020-11-29 00:12

    If you want to do that yourself, without using any external library, a clean way would be to create a template.html file with all the static content, like for example:

    
    
    
    
    $title
    
    $body
    
    
    

    Put a tag like $tag for any dynamic content and then do something like this:

    File htmlTemplateFile = new File("path/template.html");
    String htmlString = FileUtils.readFileToString(htmlTemplateFile);
    String title = "New Page";
    String body = "This is Body";
    htmlString = htmlString.replace("$title", title);
    htmlString = htmlString.replace("$body", body);
    File newHtmlFile = new File("path/new.html");
    FileUtils.writeStringToFile(newHtmlFile, htmlString);
    

    Note: I used org.apache.commons.io.FileUtils for simplicity.

提交回复
热议问题