karolsojko
karolsojko

Reputation: 721

How to output formatted html in java

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

Answers (4)

Michael
Michael

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

James Kingsbery
James Kingsbery

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

paxdiablo
paxdiablo

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 &amp; and < to &lt;.

Upvotes: 1

Jesper
Jesper

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

Related Questions