In a Servlet, I am building a very large amount of HTML content in a StringBuilder that, at the end, needs to be written to the response's PrintWriter. In order to use a PrintWriter, it must first call StringBuilder's toString() method to get the content as a String. But this unnecessarily duplicates the content. Is there some way to directly write from the StringBuilder since it already is holding the content?
PrintWriter can accept a CharSequence, but the documentation states it calls the CharSequence's toString(), so it doesn't really help.
The only clear way I can see is to use StringBuilder's charAt(i) method to get and write one character at a time, but would this be an improvement?
Writing Text to a File (.NET Framework 1.1) Just open the file and apply the ToString to your StringBuilder: StringBuilder sb = new StringBuilder(); sb. Append(......); StreamWriter sw = new StreamWriter("\\hereIAm. txt", true); sw.
Converting a String to StringBuilder The append() method of the StringBuilder class accepts a String value and adds it to the current object. To convert a String value to StringBuilder object just append it using the append() method.
StringBuilder needs toString() to convert the mutable sequence of characters to String. So technically, to return a StringBuilder obj from a method returning String, you have to convert the StringBuilder to String using toString().
The toString() method of the StringBuilder class is the inbuilt method used to return a string representing the data contained by StringBuilder Object. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by toString().
As an alternative, you could drop the StringBuilder and use a StringWriter and a PrintWriter.
You could just write to the PrintWriter in the first place rather than to the StringBuilder...
Using charAt
would definitely not help you. It would yield very poor performance to do it this way.
If you really want to proceed in that direction you could use the StringBuilder.subString(start,end)
method. This method will allow you to read for example 1000 characters at a time and print it to the PrintWriter...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With