Reputation: 721
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) ?
Upvotes: 3
Views: 4990
Reputation: 35341
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:
StringBuilder sb = new StringBuilder();
FileReader in = null;
try {
in = new FileReader(path);
int read;
char buf[] = new char[4096];
while ((read = in.read(buf)) != -1) {
sb.append(buf, 0, read);
}
} catch (Exception e) {
return e.getMessage();
} finally {
in.close();
}
String result = sb.toString();
Upvotes: 1
Reputation: 7486
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.
Upvotes: 0
Reputation: 881313
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 <
.
Upvotes: 1
Reputation: 206796
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 a String
in a loop:
try {
BufferedReader bufferReader = new BufferedReader(new FileReader(path));
StringBuilder sb = new StringBuilder();
String content;
while ((content = bufferReader.readLine()) != null) {
sb.append(content);
sb.append('\n'); // Add line separator
}
bufferReader.close();
} catch (Exception e) {
return e.getMessage();
}
String result = sb.toString();
Upvotes: 5