使用Java PrintWriter编写HTML文件

时间:2017-07-01 04:05:05

标签: javascript java html

我正在尝试使用Java PrintWriter将数据写入HTML文件:

String data = "<div>There is some text here</span>";
writer.print(data);

但是当我在浏览器中打开HTML文件时,我可以看到我的文字:

<div>There is some text here</div>

编辑器将HTML文件显示为:

&lt;div&gt;There is some text here&lt;/div&gt;

我还尝试写这样的HTML文件:

String data = "&lt;div&gt;There is some text here&lt;/div&gt;";
writer.print(data);

但浏览器将文件显示为:

&lt;div&gt;There is some text here&lt;/div&gt;

有人可以解释我应该将数据写入HTML文件以获得正确的结果&gt;?

2 个答案:

答案 0 :(得分:3)

您是否将ContentType设置为text / html?如下所示。

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<div>There is some text here</div>");

答案 1 :(得分:0)

正如我所做的评论,你最好写一个MCVE,以便我们能更好地找到你的问题。另外,提供您正在使用的编辑器以及您对编辑器的配置。

根据您提供的信息,直接回答您的问题,您可以使用下面的PrintWriter

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Test {
    public static void main(String args[]){
        try {
            File file = new File("demo.html");
            String data = "<div>There is some text here</span>";
            PrintWriter writer = new PrintWriter(file);
            writer.write(data);
            writer.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

它会在我的环境中的demo.html上生成<div>There is some text here</span>(你想使用div或span?)。但是,我也可以将输出转换为编辑器中的&lt;div&gt;There is some text here&lt;/span&gt;。所以问题来了,你能确定它不是编辑器的问题吗?让我告诉您如何使用我的编辑器将<div>There is some text here</span>显示为&lt;div&gt;There is some text here&lt;/span&gt;

  1. 使用notepad ++
  2. 安装“Html标签”插件
  3. 选择html文字 - &gt;插件 - &gt; Html标签 - &gt;编码实体