Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a StringBuilder to a Writer, without toString()

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?

like image 774
worpet Avatar asked Sep 24 '12 21:09

worpet


People also ask

How do I write a file using String builder?

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.

How do you convert a String to a StringBuilder?

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.

Do I need to convert StringBuilder to String?

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

What does StringBuilder toString do?

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


2 Answers

As an alternative, you could drop the StringBuilder and use a StringWriter and a PrintWriter.

like image 98
ChristopheD Avatar answered Oct 08 '22 02:10

ChristopheD


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

like image 21
Mathias Schwarz Avatar answered Oct 08 '22 02:10

Mathias Schwarz