java中如何输出格式化的html
我正在阅读这样的 html 文件:
try {
BufferedReader bufferReader = new BufferedReader(new FileReader(path));
String content;
while((content = bufferReader.readLine()) != null) {
result += content;
}
bufferReader.close();
} catch (Exception e) {
return e.getMessage();
}
我想将其显示在 GWT textArea 中,在其中我将其作为字符串提供。但该字符串失去了缩进,并以单行文本的形式出现。有没有办法以正确的格式显示它(带缩进)?
I'm reading an html file like this:
try {
BufferedReader bufferReader = new BufferedReader(new FileReader(path));
String content;
while((content = bufferReader.readLine()) != null) {
result += content;
}
bufferReader.close();
} catch (Exception e) {
return e.getMessage();
}
And I want to display it in a GWT textArea, in which i give it to as a String. But the string loses indentations and comes out as a one-liner text. Is there a way to display it properly formatted (with indentations) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可能是因为
readLine()
截断了行尾字符。为每一行再次添加它们。除此之外,在循环中使用
StringBuilder
而不是使用+=
来处理String
:That's probably because
readLine()
chops off the end-of-line character(s). Add them yourself again for each line.Besides that, use a
StringBuilder
instead of using+=
to aString
in a loop:好吧,假设您的 textArea 能够理解 HTML(我具体不了解 GWT),为什么不在其前面加上
?
您可能仍然需要转义所有 HTML 特殊字符,例如将
&
转义为&
以及将<
转义为<。
Well, assuming your textArea understands HTML (I don't know GWT specifically), why don't you prefix it with
<pre>
then append</pre>
?You'll may still have to escape all the HTML special characters such as
&
to&
and<
to<
.使用 FileReader 可能会更有效——没有理由必须逐行读取文本。正如 Jesper 所建议的,使用 StringBuilder 来构建 String 会更高效。此外,使用 FileReader,您不必手动附加任何换行符:
It might be more efficient to use a FileReader instead--there's no reason why you have to read the text line-by-line. Like Jesper suggested, using a StringBuilder to build your String is more efficient. Also, with FileReader, you don't have to manually append any newlines:
如果您的 HTML 恰好是 XHTML,那么您可以尝试的一件事是将其放入 XML 解析器(例如 jdom 或 dom4j)中,它们通常具有一些“漂亮打印”选项。
If your HTML happens to be XHTML, then one thing you can try is to put it into an XML parser such as jdom or dom4j, which usually has some "pretty-print" option.