Is there an easy way to concatenate several lines of text into a string without constantly appending a newline?
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());
AFAIK there's no library class that allows you to do so.
The following does the work though:
class DesiredStringThinger {
StringBuilder text = new StringBuilder();
public void append(String s) { text.append(s).append("\n"); }
@Override
public String toString() { return text.toString(); }
}
public String createString () {
StringBuilder sb = new StringBuilder ();
String txt = appendLine("firstline", sb).appendLine("2ndLine", sb).toString();
}
private StringBuilder appendLine (String line, StringBuilder sb) {
String lsp = System.getProperty("line.separator");
return sb.append (line).append (lsp);
}