Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 895
karolsojko Avatar asked Jun 20 '26 00:06

karolsojko


1 Answers

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();
like image 181
Jesper Avatar answered Jun 22 '26 14:06

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!