3

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) ?

4 Answers 4

5

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.