Cappuccino : String & StringBuffer & StringWriter
Cappuccino : String & StringBuffer & StringWriter
1. In general, the String concatenation operation goes like this: Take the operands on both sides of the plus; if the right-hand operand is not a String then convert it using the toString() operator, then create a new String that is a combination of the two. One method for creating this new temporary string is to create a new StringBuffer, append the strings, and then call toString().
2. String concatenation operation
01: String buf = “”;
02: String line = null;
03: while ( (line = br.readLine()) != null)
04: {
05: if (line.startsWith(“#”) == false)
06: buf += (line + “\n”);
07: }
3. StringBuffer
02: String line = null;
03: while ( (line = br.readLine()) != null)
04: {
05: if (line.startsWith(“#”) == false)
06: {
07: buf.append(line);
08: buf.append(‘\n’);
09: }
10: }
4. java.io.StringWriter
public class StringWriter extends Writer
A character stream that collects its output in a string buffer, which can then be used to construct a string.
Closing a StringWriter has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.
5. File Reading Performance Table
METHOD 2,000-LINE FILE 10,000-LINE FILE 20,000-LINE FILE
Concatenation with ‘+’ 12,800ms 229,210ms 819,270 ms
StringBuffer append() 440ms 1,540ms 2,530ms