使用Java编写HTML文件 [英] Write HTML file using Java

查看:679
本文介绍了使用Java编写HTML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的Java应用程序在一个文件中编写HTML代码。现在,我很难用java.io.BufferedWriter类编码HTML标签。例如:

  BufferedWriter bw = new BufferedWriter(new FileWriter(file)); 
< head>< html>< head>体>< / HTML>中);
bw.close();

有没有更简单的方法来做到这一点,因为我必须创建表格,而且它变得非常不方便如果你想自己做,而不使用任何外部库,我认为一个干净的方法是创建一个包含所有静态内容的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-Typecontent =text / html; charset = UTF-8>
< title> $ title< / title>
< / head>
< body> $ body
< / body>
< / html>

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

 文件htmlTemplateFile = new File(path / template.html); 
String htmlString = FileUtils.readFileToString(htmlTemplateFile);
String title =新页面;
String body =This is Body;
htmlString = htmlString.replace($ title,title);
htmlString = htmlString.replace($ body,body);
文件newHtmlFile =新文件(path / new.html);
FileUtils.writeStringToFile(newHtmlFile,htmlString);

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


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:

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();

Is there any easier way to do this, as I have to create tables and it is becoming very inconvenient?

解决方案

If you want to do that yourself, without using any external library, I think 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>

Putting 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.

这篇关于使用Java编写HTML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆