Write HTML file using Java

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

    A few months ago I had the same problem and every library I found provides too much functionality and complexity for my final goal. So I end up developing my own library - HtmlFlow - that provides a very simple and intuitive API that allows me to write HTML in a fluent style. Check it here: https://github.com/fmcarvalho/HtmlFlow (it also supports dynamic binding to HTML elements)

    Here is an example of binding the properties of a Task object into HTML elements. Consider a Task Java class with three properties: Title, Description and a Priority and then we can produce an HTML document for a Task object in the following way:

    import htmlflow.HtmlView;
    
    import model.Priority;
    import model.Task;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.PrintStream;
    
    public class App {
    
        private static HtmlView taskDetailsView(){
            HtmlView taskView = new HtmlView<>();
            taskView
                    .head()
                    .title("Task Details")
                    .linkCss("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css");
            taskView
                    .body().classAttr("container")
                    .heading(1, "Task Details")
                    .hr()
                    .div()
                    .text("Title: ").text(Task::getTitle)
                    .br()
                    .text("Description: ").text(Task::getDescription)
                    .br()
                    .text("Priority: ").text(Task::getPriority);
            return taskView;
        }
    
        public static void main(String [] args) throws IOException{
            HtmlView taskView = taskDetailsView();
            Task task =  new Task("Special dinner", "Have dinner with someone!", Priority.Normal);
    
            try(PrintStream out = new PrintStream(new FileOutputStream("Task.html"))){
                taskView.setPrintStream(out).write(task);
                Desktop.getDesktop().browse(URI.create("Task.html"));
            }
        }
    }
    

提交回复
热议问题