使用Java编写HTML文件

hos*_*ney 45 html java

我希望我的Java应用程序在文件中编写HTML代码.现在,我正在使用java.io.BufferedWriter类对HTML标签进行硬编码.例如:

BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write("<html><head><title>New Page</title></head><body><p>This is Body</p></body></html>");
bw.close();
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法来做到这一点,因为我必须创建表格,它变得非常不方便?

Mar*_*vic 43

如果你想自己做,不使用任何外部库,一个干净的方法是创建一个template.html包含所有静态内容的文件,例如:

<!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>
Run Code Online (Sandbox Code Playgroud)

$tag为任何动态内容添加标记,然后执行以下操作:

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);
Run Code Online (Sandbox Code Playgroud)

注意:为简单起见,我使用了org.apache.commons.io.FileUtils.

  • 对于Java8,传递额外的Charset.forName("UTF-8"),因为不推荐使用不带字符集的readFileToString. (3认同)
  • 也可以使用MessageFormat进行替换:`String template = FileUtils.readFileToString(htmlTemplateFile); String title ="New Page"; String body ="这是身体"; 字符串htmlString = MessageFormat.format(模板,标题,正文);`和`template`则应包含`{0}`表示`title`,`{1}`表示`body`. (2认同)

Mig*_*boa 11

几个月前,我遇到了同样的问题,我找到的每个库都为我的最终目标提供了太多的功能和复杂性.所以我最终开发了自己的库 - HtmlFlow - 它提供了一个非常简单直观的API,允许我以流畅的方式编写HTML.在这里查看:https://github.com/fmcarvalho/HtmlFlow(它还支持动态绑定到HTML元素)

以下是将Task对象的属性绑定到HTML元素的示例.考虑一个TaskJava类具有三个属性:Title,DescriptionPriority,然后我们就可以生成HTML文档的Task按以下方式对象:

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<Task> taskDetailsView(){
        HtmlView<Task> 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<Task> 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"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ sn-ushakov DONE.只需发布1.1版.使用MIT许可证和一些小修复. (5认同)
  • GPL的问题在于它过于严格。如果您仅使用GPL许可的任何代码,它也需要您根据GPL披露所有项目。对于业余或大学编程而言,这可能不是问题,但对于与业务相关的编程而言,则可能是一个相当大的问题。因此,为了使您的库对业务更加友好,我建议您至少将许可证更改为LGPL,这不需要您开源所有项目,而只需要向库公开您的改进。BSD,MIT,Apache,Eclipse ... (3认同)

PAT*_*ume 7

Velocity是写这种东西的好人选.
它允许您将html和数据生成代码尽可能分开.


RRa*_*ley 7

您可以使用基于jsoupwffweb(HTML5).

jsoup的示例代码: -

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

版画

<html>
 <head></head>
 <body class=" body-styles-cls">
  <div></div>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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");
Run Code Online (Sandbox Code Playgroud)

打印(缩小格式): -

<html>
<head></head>
<body class="body-styles-cls">
    <div></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


npe*_*low 6

我强烈建议你使用一种非常简单的模板语言,如Freemarker