Cómo añadir una nueva línea a StringBuilder


Tengo un StringBuilder objeto,

StringBuilder result = new StringBuilder();
result.append(someChar);

Ahora quiero añadir un carácter de nueva línea a StringBuilder. ¿Cómo puedo hacerlo?

result.append("/n"); 

No funciona. Estaba pensando en escribir una nueva línea usando Unicode. Ayudará esto? Si es así, ¿cómo puedo agregar uno?

Author: Adam Stelmaszczyk, 2013-01-26

8 answers

Debe ser

r.append("\n");

Pero te recomiendo que hagas lo siguiente,

r.append(System.getProperty("line.separator"));

System.getProperty("line.separator") le da una nueva línea dependiente del sistema en Java. También desde Java 7 hay un método que devuelve el valor directamente: System.lineSeparator()

 409
Author: Jayamohan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-03 15:40:29

Otra opción es usar Apache Commons StrBuilder, que tiene la funcionalidad que falta en StringBuilder.

StrBuilder.appendLn()

 16
Author: Half_Duplex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-03 18:00:37

El escape debe hacerse con \, no con /.

Así que r.append('\n'); o r.append("\n"); funcionará (StringBuilder tiene métodos sobrecargados para char y String tipo).

 14
Author: nhahtdh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-26 07:17:47

Puede usar line.seperator para agregar una nueva línea en

 2
Author: Rashida Hasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-01 03:21:12

También puede usar el carácter separador de líneas en String.format (Ver java.util.Formatter), que también es independiente de la plataforma.

Es decir:

result.append(String.format("%n", ""));

Si necesita agregar más espacios de línea, simplemente use:

result.append(String.format("%n%n", ""));

También puedes usar StringFormat para dar formato a toda tu cadena, con una(s) línea (s) nueva (s) al final.

result.append(String.format("%10s%n%n", "This is my string."));
 1
Author: Roxanne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-19 23:00:32

Creo una clase original que es similar a StringBuidler y puedo añadir una línea llamando al método AppendLine(String str).

public class StringBuilderPlus {

    private StringBuilder sb;

    public StringBuilderPlus(){
         sb = new StringBuilder();
    }

    public void append(String str)
    {
        sb.append(str != null ? str : "");
    }

    public void appendLine(String str)
    {
        sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
    }

    public String toString()
    {
        return sb.toString();
    }
}

Uso:

StringBuilderPlus sb = new StringBuilderPlus();
sb.appendLine("aaaaa");
sb.appendLine("bbbbb");
System.out.println(sb.toString());

Consola:

aaaaa
bbbbb
 1
Author: K.S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-20 09:57:01

Para Android, ¡Usa esto para Leer y Escribir!

private void writeToFile(String message) {
        try {
            OutputStream outputStream = openFileOutput("todoList.txt",Context.MODE_PRIVATE);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(message);
            outputStreamWriter.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readFromFile() throws IOException {

        String result = "";
        InputStream inputStream = openFileInput("todoList.txt");

        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String tempString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (tempString = bufferedReader.readLine()) != null ) {

                stringBuilder.append(tempString);
                stringBuilder.append("\n");
            }
            inputStream.close();
            result = stringBuilder.toString();
        }
        return result;
    }
 0
Author: Abhishek Sengupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-23 14:55:18

Esto también funcionará en StringBuilder

result.append("<BR />");
 0
Author: Joel George,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-04 07:39:08