Search code examples
javastringappendconcatenation

Is there an easy way to concatenate several lines of text into a string without constantly appending a newline?


So I essentially need to do this:

String text = "line1\n";
text += "line2\n";
text += "line3\n";
useString( text );

There is more involved, but that's the basic idea. Is there anything out there that might let me do something more along the lines of this though?

DesiredStringThinger text = new DesiredStringThinger();
text.append( "line1" );
text.append( "line2" );
text.append( "line3" );
useString( text.toString() );

Obviously, it does not need to work exactly like that, but I think I get the basic point across. There is always the option of writing a loop which processes the text myself, but it would be nice if there is a standard Java class out there that already does something like this rather than me needing to carry a class around between applications just so I can do something so trivial.

Thanks!


Solution

  • You can use a StringWriter wrapped in a PrintWriter:

    StringWriter stringWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(stringWriter, true);
    writer.println("line1");
    writer.println("line2");
    writer.println("line3");
    useString(stringWriter.toString());