String assembly by StringBuilder vs StringWriter and PrintWriter

Posted by CPerkins on Stack Overflow See other posts from Stack Overflow or by CPerkins
Published on 2010-06-05T14:51:08Z Indexed on 2010/06/05 15:02 UTC
Read the original article Hit count: 591

Filed under:

I recently encountered an idiom I haven't seen before: string assembly by StringWriter and PrintWriter. I mean, I know how to use them, but I've always used StringBuilder. Is there a concrete reason for preferring one over the other? The StringBuilder method seems much more natural to me, but is it just style?

I've looked at several questions here (including this one which comes closest: http://stackoverflow.com/questions/602279/stringwriter-or-stringbuilder ), but none in which the answers actually address the question of whether there's a reason to prefer one over the other for simple string assembly.

This is the idiom I've seen and used many many times: string assembly by StringBuilder:


    public static String newline = System.getProperty("line.separator");
    public String viaStringBuilder () {
       StringBuilder builder = new StringBuilder();
       builder.append("first thing" + newline);
       builder.append("second thing" + newline);
       // ... several things
       builder.append("last thing" + newline);
       return builder.toString();
    }

And this is the new idiom: string assembly by StringWriter and PrintWriter:


    public String viaWriters() {
       StringWriter stringWriter = new StringWriter();
       PrintWriter printWriter = new PrintWriter(stringWriter);
       printWriter.println("first thing");
       printWriter.println("second thing");
       // ... several things
       printWriter.println("last thing");
       printWriter.flush();
       printWriter.close();
       return stringWriter.toString();
    }

© Stack Overflow or respective owner

Related posts about java