Java StringBuilder 每次都将内容追加到新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19813431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:25:16  来源:igfitidea点击:

StringBuilder append content to a new line every time

javastringbuilder

提问by Dark Knight

I am building a validation routine that validates contents and then gives warning (for failures) in form of StringBuilder. Say in below code I am checking lower bound for values paramX and paramY.

我正在构建一个验证例程,它验证内容,然后以StringBuilder 的形式发出警告(对于失败)。在下面的代码中说,我正在检查值 paramX 和 paramY 的下限。

 StringBuilder sb= new StringBuilder();

        if(paramX<10){
            sb.append("paramX cannot be less than 10 ");
        }

        if(paramY<20){
            sb.append("paramY cannot be less than 20 ");
        }

        System.out.println(sb);

It gives output as: paramX cannot be less than 10 paramY cannot be less than 20

它给出的输出为:paramX 不能小于 10 paramY 不能小于 20

but i want output such that, each appended String will be printed on new line. Like below.

但我想要这样的输出,每个附加的字符串都将打印在新行上。像下面。

paramX cannot be less than 10 

paramY cannot be less than 20

I used following workarounds, but ended up repeating same code again and again(Which i don't want to).

我使用了以下解决方法,但最终一次又一次地重复相同的代码(我不想这样做)。

sb.append(System.getProperty("line.separator")); // Add Explicit line separator each time
sb.append("\n");
sb.append("paramX cannot be less than 10 \n");

Is there a simpler way to do it?

有没有更简单的方法来做到这一点?

采纳答案by Dark Knight

Just thought of sharing the new feature of jdk 8 i used for achieving same result. Using StringJoiner we can construct a sequence of characters separated by a delimiter.

只是想分享我用来实现相同结果的 jdk 8 的新功能。使用 StringJoiner 我们可以构造由分隔符分隔的字符序列。

StringJoiner formattedString= new StringJoiner("\n"); 
formattedString.add("XXX");
formattedString.add("YYY");
System.out.println(formattedString);  

回答by subash

simply append directly...

只需直接追加...

        if(paramX<10){
            sb.append("paramX cannot be less than 10 \n ");
        }

        if(paramY<20){
            sb.append("paramY cannot be less than 20 \n ");
        }

回答by StuPointerException

If you don't want to do it over and over then write a helper method:

如果您不想一遍又一遍地执行此操作,请编写一个辅助方法:

public void appendString(StringBuilder builder, String value) {
    builder.append(value + System.lineSeparator());
}

Then call:

然后调用:

if(paramX<10){
    appendString(sb, "paramX cannot be less than 10 ");
}

This way you only have a single place to maintain if you need to change the output format for the errors.

这样,如果您需要更改错误的输出格式,您只需维护一个地方。

回答by rzymek

First of all you need to include the newline character(\n) at the end of every .append()yourself:

首先,您需要\n在每个.append()自己的末尾包含换行符():

sb.append("paramX cannot be less than 10 \n");

As for repeating you new-line logicjust wrap it in a method:

至于重复换行逻辑,只需将其包装在一个方法中:

public void append(StringBuilder sb, Object value) {
    sb.append(value).append(System.getProperty("line.separator")).append('\n');
}

And use it like:

并像这样使用它:

if(paramX < 10){
    append(sb, "paramX cannot be less than 10");
}

回答by Nathan Hughes

The simple way would be to keep a list of errors rather than concatenating them as you go. That would help to maintain a separation of concerns between the logical errors and their presentation.

简单的方法是保留一个错误列表,而不是在执行时将它们连接起来。这将有助于保持逻辑错误与其表示之间的关注点分离。

See how Spring validation works: you have an Errors object that keeps a list of errors, and a separate message source object that fills in the user-visible messages for the different errors.

了解 Spring 验证的工作原理:您有一个 Errors 对象,用于保存错误列表,以及一个单独的消息源对象,用于填充不同错误的用户可见消息。

回答by Bohemian

Just use \n- it will work everywhere. Also, it looks like you want to conditionally add a line feed if there are twomessages:

只需使用\n- 它会在任何地方工作。此外,如果有两条消息,您似乎想有条件地添加换行符:

StringBuilder sb = new StringBuilder();

if (paramX<10) {
    sb.append("paramX cannot be less than 10 ");
}

if (paramY<20) {
    if (!sb.length() > 0) // only add newline if needed
        sb.append('\n');
    sb.append("paramY cannot be less than 20 ");
}

回答by Chris M

You could try using a PrintStream as it has an println(String string) method which add the new line automatically.

您可以尝试使用 PrintStream,因为它有一个 println(String string) 方法,可以自动添加新行。

Something like this.

像这样的东西。

ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bos);
ps.println("Line 1");
ps.println("Line 2");
ps.flush();
String message = new String(bos.toByteArray());
System.out.println(message);

回答by Half_Duplex

Another option is to use Apache Commons StrBuilder, which has the functionality that you're looking for.

另一种选择是使用 Apache Commons StrBuilder,它具有您正在寻找的功能。

StrBuilder.appendLn()

StrBuilder.appendLn()