Write HTML file using Java

前端 未结 10 853
我寻月下人不归
我寻月下人不归 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:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>$title</title>
    </head>
    <body>$body
    </body>
    </html>
    

    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.

    0 讨论(0)
  • 2020-11-29 00:14

    I would highly recommend you use a very simple templating language such as Freemarker

    0 讨论(0)
  • 2020-11-29 00:17

    You can use jsoup or wffweb (HTML5) based.

    Sample code for jsoup:-

    Document doc = Jsoup.parse("<html></html>");
    doc.body().addClass("body-styles-cls");
    doc.body().appendElement("div");
    System.out.println(doc.toString());
    

    prints

    <html>
     <head></head>
     <body class=" body-styles-cls">
      <div></div>
     </body>
    </html>
    

    Sample code for wffweb:-

    Html html = new Html(null) {{
        new Head(this);
        new Body(this,
            new ClassAttribute("body-styles-cls"));
    }};
    
    Body body = TagRepository.findOneTagAssignableToTag(Body.class, html);
    body.appendChild(new Div(null));
    
    System.out.println(html.toHtmlString());
    //directly writes to file
    html.toOutputStream(new FileOutputStream("/home/user/filepath/filename.html"), "UTF-8");
    

    prints (in minified format):-

    <html>
    <head></head>
    <body class="body-styles-cls">
        <div></div>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-29 00:22

    It really depends on the type of HTML file you're creating.

    For such tasks, I use to create an object, serialize it to XML, then transform it with XSL. The pros of this approach are:

    • The strict separation between source code and HTML template,
    • The possibility to edit HTML without having to recompile the application,
    • The ability to serve different HTML in different cases based on the same XML, or even serve XML directly when needed (for a further deserialization for example),
    • The shorter amount of code to write.

    The cons are:

    • You must know XSLT and know how to implement it in Java.
    • You must write XSLT (and it's torture for many developers).
    • When transforming XML to HTML with XSLT, some parts may be tricky. Few examples: <textarea/> tags (which make the page unusable), XML declaration (which can cause problems with IE), whitespace (with <pre></pre> tags etc.), HTML entities (&nbsp;), etc.
    • The performance will be reduced, since serialization to XML wastes lots of CPU resources and XSL transformation is very costly too.

    Now, if your HTML is very short or very repetitive or if the HTML has a volatile structure which changes dynamically, this approach must not be taken in account. On the other hand, if you serve HTML files which have all a similar structure and you want to reduce the amount of Java code and use templates, this approach may work.

    0 讨论(0)
  • 2020-11-29 00:24

    Velocity is a good candidate for writing this kind of stuff.
    It allows you to keep your html and data-generation code as separated as possible.

    0 讨论(0)
  • 2020-11-29 00:24

    I had also problems in finding something simple to satisfy my needs so I decided to write my own library (with MIT license). It's mainly based on composite and builder pattern.

    A basic declarative example is:

    import static com.github.manliogit.javatags.lang.HtmlHelper.*;
    
    html5(attr("lang -> en"),
      head(
        meta(attr("http-equiv -> Content-Type", "content -> text/html; charset=UTF-8")),
        title("title"),
        link(attr("href -> xxx.css", "rel -> stylesheet"))
      )
    ).render();
    

    A fluent example is:

    ul()
      .add(li("item 1"))
      .add(li("item 2"))
      .add(li("item 3"))     
    

    You can check more examples here

    I also created an on line converter to transform every html snippet (from complex bootstrap template to simple single snippet) on the fly (i.e. html -> javatags)

    0 讨论(0)
提交回复
热议问题