Cadena multilínea de Java


Viniendo de Perl, estoy seguro de que me falta el medio "here-document"de crear una cadena de varias líneas en el código fuente:

$string = <<"EOF"  # create a three-line string
text
text
text
EOF

En Java, tengo que tener comillas engorrosas y signos de más en cada línea mientras concateno mi cadena multilínea desde cero.

¿Cuáles son algunas alternativas mejores? Definir mi cadena en un archivo de propiedades?

Edit : Dos respuestas dicen StringBuilder.append () es preferible a la notación plus. ¿Podría alguien explicar por qué piensan así? No me parece más preferible para nada. Estoy buscando una manera de evitar el hecho de que las cadenas multilínea no son una construcción de lenguaje de primera clase, lo que significa que definitivamente no quiero reemplazar una construcción de lenguaje de primera clase (concatenación de cadenas con plus) con llamadas a métodos.

Editar: Para aclarar más mi pregunta, no me preocupa en absoluto el rendimiento. Me preocupan los problemas de mantenimiento y diseño.

Author: skiphoppy, 2009-05-18

30 answers

Stephen Colebourne ha creado una propuesta para agregar cadenas de varias líneas en Java 7.

Además, Groovy ya tiene soporte para cadenas multilíneas.

 95
Author: Paul Morie,
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-12-01 12:34:43

Parece que quieres hacer un literal multilínea, que no existe en Java.

Su mejor alternativa va a ser cadenas que son sólo +'d juntos. Algunas otras opciones que la gente ha mencionado (StringBuilder, String.formato, Cadena.join) solo sería preferible si empezaras con una matriz de cadenas.

Considere esto:

String s = "It was the best of times, it was the worst of times,\n"
         + "it was the age of wisdom, it was the age of foolishness,\n"
         + "it was the epoch of belief, it was the epoch of incredulity,\n"
         + "it was the season of Light, it was the season of Darkness,\n"
         + "it was the spring of hope, it was the winter of despair,\n"
         + "we had everything before us, we had nothing before us";

Versus StringBuilder:

String s = new StringBuilder()
           .append("It was the best of times, it was the worst of times,\n")
           .append("it was the age of wisdom, it was the age of foolishness,\n")
           .append("it was the epoch of belief, it was the epoch of incredulity,\n")
           .append("it was the season of Light, it was the season of Darkness,\n")
           .append("it was the spring of hope, it was the winter of despair,\n")
           .append("we had everything before us, we had nothing before us")
           .toString();

Versus String.format():

String s = String.format("%s\n%s\n%s\n%s\n%s\n%s"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

Versus Java8 String.join():

String s = String.join("\n"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

Si desea la nueva línea para su sistema en particular, debe usar System.getProperty("line.separator"), o puede usar %n en String.format.

Otra opción es poner el recurso en un archivo de texto, y simplemente leer el contenido de ese archivo. Esto sería preferible para cadenas muy grandes para evitar hinchar innecesariamente sus archivos de clase.

 405
Author: Kip,
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-02-24 01:42:35

En Eclipse si activa la opción "Escape text when pasting into a string literal" (en Preferencias > Java > Editor > Typing) y pega una cadena de varias líneas entre comillas, agregará automáticamente " y \n" + para todas sus líneas.

String str = "paste your text here";
 180
Author: Monir,
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
2011-12-22 15:29:06

Este es un hilo antiguo, pero una nueva solución bastante elegante (con solo un inconveniente) es usar una anotación personalizada.

Compruebe: http://www.adrianwalker.org/2011/12/java-multiline-string.html

Edit: La URL anterior parece estar rota. Un proyecto inspirado en ese trabajo está alojado en GitHub:

Https://github.com/benelog/multiline

public final class MultilineStringUsage {

  /**
  <html>
    <head/>
    <body>
      <p>
        Hello<br/>
        Multiline<br/>
        World<br/>
      </p>
    </body>
  </html>
  */
  @Multiline
  private static String html;

  public static void main(final String[] args) {
    System.out.println(html);
  }
}

El inconveniente es que tiene que activar la anotación correspondiente (proporcionada) procesador.

Y probablemente tengas que configurar Eclipse para que no reformatee automáticamente tus comentarios de Javadoc.

Uno puede encontrar esto raro (los comentarios de Javadoc no están diseñados para incrustar nada más que comentarios), pero como esta falta de cadena multilínea en Java es realmente molesta al final, me parece que esta es la solución menos peor.

 83
Author: SRG,
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-09-27 18:53:24

Otra opción puede ser almacenar cadenas largas en un archivo externo y leer el archivo en una cadena.

 55
Author: Josh Curren,
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
2009-05-18 16:38:29

Esto es algo que debes nunca usar sin pensar en lo que está haciendo. Pero para los scripts de una sola vez he utilizado esto con gran éxito:

Ejemplo:

    System.out.println(S(/*
This is a CRAZY " ' ' " multiline string with all sorts of strange 
   characters!
*/));

Código:

// From: http://blog.efftinge.de/2008/10/multi-line-string-literals-in-java.html
// Takes a comment (/**/) and turns everything inside the comment to a string that is returned from S()
public static String S() {
    StackTraceElement element = new RuntimeException().getStackTrace()[1];
    String name = element.getClassName().replace('.', '/') + ".java";
    StringBuilder sb = new StringBuilder();
    String line = null;
    InputStream in = classLoader.getResourceAsStream(name);
    String s = convertStreamToString(in, element.getLineNumber());
    return s.substring(s.indexOf("/*")+2, s.indexOf("*/"));
}

// From http://www.kodejava.org/examples/266.html
private static String convertStreamToString(InputStream is, int lineNum) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null; int i = 1;
    try {
        while ((line = reader.readLine()) != null) {
            if (i++ >= lineNum) {
                sb.append(line + "\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return sb.toString();
}
 42
Author: Bob Albright,
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
2009-11-03 15:55:30

String.join

Java 8 agregó un nuevo método estático a java.lang.String que ofrece una alternativa ligeramente mejor:

String.join( CharSequence delimiter , CharSequence... elements )

Usándolo:

String s = String.join(
    System.getProperty("line.separator"),
    "First line.",
    "Second line.",
    "The rest.",
    "And the last!"
);
 35
Author: icza,
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-22 23:11:16

Si define sus cadenas en un archivo de propiedades, se verá mucho peor. IIRC, se verá como:

string:text\u000atext\u000atext\u000a

Generalmente es una idea razonable no incrustar cadenas grandes en el código fuente. Es posible que desee cargarlos como recursos, tal vez en XML o en un formato de texto legible. Los archivos de texto pueden leerse en tiempo de ejecución o compilarse en código fuente Java. Si terminas colocándolos en la fuente, te sugiero poner el + al frente y omitir nuevas líneas innecesarias:

final String text = ""
    +"text "
    +"text "
    +"text"
;

Si lo haces tener nuevas líneas, es posible que desee algunos de join o método de formato:

final String text = join("\r\n"
    ,"text"
    ,"text"
    ,"text"
);
 19
Author: Tom Hawtin - tackline,
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
2009-05-18 16:47:43

Las ventajas se convierten a StringBuilder.append, excepto cuando ambas cadenas son constantes para que el compilador pueda combinarlas en tiempo de compilación. Al menos, así es como es en el compilador de Sun, y sospecharía que la mayoría, si no todos los demás compiladores, harían lo mismo.

Así que:

String a="Hello";
String b="Goodbye";
String c=a+b;

Normalmente genera exactamente el mismo código que:

String a="Hello";
String b="Goodbye":
StringBuilder temp=new StringBuilder();
temp.append(a).append(b);
String c=temp.toString();

Por otro lado:

String c="Hello"+"Goodbye";

Es lo mismo que:

String c="HelloGoodbye";

Es decir, no hay penalización en romper sus literales de cadena a través múltiples líneas con signos más para facilitar la lectura.

 17
Author: Jay,
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
2009-05-19 00:37:21

En el IDE IntelliJ solo necesita escribir:

""

Luego coloque el cursor dentro de las comillas y pegue la cadena. El IDE lo expandirá en múltiples líneas concatenadas.

 12
Author: nurettin,
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-08 16:28:13
String newline = System.getProperty ("line.separator");
string1 + newline + string2 + newline + string3

Pero, la mejor alternativa es usar Cadena.formato

String multilineString = String.format("%s\n%s\n%s\n",line1,line2,line3);
 10
Author: Tom,
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
2011-12-22 15:08:03

Lamentablemente, Java no tiene literales de cadena multilínea. Tienes que concatenar literales de cadena (usando + o StringBuilder siendo los dos enfoques más comunes para esto) o leer la cadena desde un archivo separado.

Para literales de cadena de varias líneas grandes, me inclinaría a usar un archivo separado y leerlo en using getResourceAsStream() (un método de la clase Class). Esto hace que sea fácil encontrar el archivo, ya que no tiene que preocuparse por el directorio actual frente a donde se instaló su código. También facilita el empaquetado, ya que puede almacenar el archivo en su archivo jar.

Supongamos que estás en una clase llamada Foo. Simplemente haga algo como esto:

Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);

La otra molestia es que Java no tiene un método estándar de "leer todo el texto de este lector en una cadena". Sin embargo, es bastante fácil de escribir:

public static String readAll(Reader input) {
    StringBuilder sb = new StringBuilder();
    char[] buffer = new char[4096];
    int charsRead;
    while ((charsRead = input.read(buffer)) >= 0) {
        sb.append(buffer, 0, charsRead);
    }
    input.close();
    return sb.toString();
}
 9
Author: Laurence Gonsalves,
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
2009-05-18 22:53:50

Dado que Java (todavía) no soporta cadenas multilíneas, la única manera por ahora es hackearlas usando una de las técnicas antes mencionadas. Construí el siguiente script Python usando algunos de los trucos mencionados anteriormente:

import sys
import string
import os

print 'new String('
for line in sys.stdin:
    one = string.replace(line, '"', '\\"').rstrip(os.linesep)
    print '  + "' + one + ' "'
print ')'

Pon eso en un archivo llamado javastringify.py y tu cadena en un archivo mystring.txt y ejecutarlo de la siguiente manera:

cat mystring.txt | python javastringify.py

Luego puede copiar la salida y pegarla en su editor.

Modifique esto según sea necesario para manejar cualquier caso especial, pero esto funciona para mis necesidades. Espero que esto ayude!

 9
Author: scorpiodawg,
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
2011-02-21 18:22:12

Puede usar scala-code, que es compatible con java, y permite cadenas multilíneas encerradas con""":

package foobar
object SWrap {
  def bar = """John said: "This is
  a test
  a bloody test,
  my dear." and closed the door.""" 
}

(observe las comillas dentro de la cadena) y desde java:

String s2 = foobar.SWrap.bar ();

Si esto es más cómodo ...?

Otro enfoque, si a menudo maneja texto largo, que debe colocarse en su código fuente, podría ser un script, que toma el texto de un archivo externo, y lo envuelve como una cadena-java-multilínea como esta:

sed '1s/^/String s = \"/;2,$s/^/\t+ "/;2,$s/$/"/' file > file.java

Para que puedas cortar y pegar fácilmente en su fuente.

 9
Author: user unknown,
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-06-20 16:28:25

En realidad, la siguiente es la implementación más limpia que he visto hasta ahora. Utiliza una anotación para convertir un comentario en una variable de cadena...

/**
  <html>
    <head/>
    <body>
      <p>
        Hello<br/>
        Multiline<br/>
        World<br/>
      </p>
    </body>
  </html>
  */
  @Multiline
  private static String html;

Entonces, el resultado final es que la variable html contiene la cadena multilínea. Sin comillas, sin ventajas, sin comas, solo cadena pura.

Esta solución está disponible en la siguiente URL... http://www.adrianwalker.org/2011/12/java-multiline-string.html

Espero que ayude!

 7
Author: Rodney P. Barbati,
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
2014-07-14 01:32:44
    import org.apache.commons.lang3.StringUtils;

    String multiline = StringUtils.join(new String[] {
        "It was the best of times, it was the worst of times ", 
        "it was the age of wisdom, it was the age of foolishness",
        "it was the epoch of belief, it was the epoch of incredulity",
        "it was the season of Light, it was the season of Darkness",
        "it was the spring of hope, it was the winter of despair",
        "we had everything before us, we had nothing before us"
    }, "\n");
 6
Author: Mykhaylo Adamovych,
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
2014-06-03 07:17:16

Puede concatenar sus anexos en un método separado como:

public static String multilineString(String... lines){
   StringBuilder sb = new StringBuilder();
   for(String s : lines){
     sb.append(s);
     sb.append ('\n');
   }
   return sb.toStirng();
}

De cualquier manera, prefiera StringBuilder a la notación más.

 6
Author: user54579,
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-06 15:57:46

Véase Java Stringfier. Convierte tu texto en un bloque java StringBuilder escapando si es necesario.

 6
Author: Leo,
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-25 12:08:06

Una alternativa que aún no he visto como respuesta es la java.io.PrintWriter.

StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
writer.println("It was the best of times, it was the worst of times");
writer.println("it was the age of wisdom, it was the age of foolishness,");
writer.println("it was the epoch of belief, it was the epoch of incredulity,");
writer.println("it was the season of Light, it was the season of Darkness,");
writer.println("it was the spring of hope, it was the winter of despair,");
writer.println("we had everything before us, we had nothing before us");
String string = stringWriter.toString();

También el hecho de que java.io.BufferedWriter tiene un método newLine() no se menciona.

 5
Author: BalusC,
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
2009-11-03 16:06:24

Si te gusta la guayaba de Google tanto como a mí, puede dar una representación bastante limpia y una manera agradable y fácil de no codificar tus caracteres de nueva línea también:

String out = Joiner.on(newline).join(ImmutableList.of(
    "line1",
    "line2",
    "line3"));
 5
Author: Dan Lo Bianco,
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
2012-07-10 17:08:27

Una solución bastante eficiente e independiente de la plataforma sería usar la propiedad system para separadores de línea y la clase StringBuilder para construir cadenas:

String separator = System.getProperty("line.separator");
String[] lines = {"Line 1", "Line 2" /*, ... */};

StringBuilder builder = new StringBuilder(lines[0]);
for (int i = 1; i < lines.length(); i++) {
    builder.append(separator).append(lines[i]);
}
String multiLine = builder.toString();
 4
Author: Andreas_D,
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
2014-05-25 18:26:14

JEP 326: Raw String Literals implementará Cadenas multilíneas, por lo que podrá escribir algo como:

String s = `
    text
    text
    text
  `;

Se planea como una vista previa de características en JDK 12.

 4
Author: alostale,
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-01 11:10:02

¿Definir mi cadena en un archivo de propiedades?

Las cadenas multilínea no están permitidas en los archivos de propiedades. Puede usar \n en archivos de propiedades, pero no creo que sea una gran solución en su caso.

 3
Author: Kip,
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
2009-05-18 16:43:20

Una buena opción.

import static some.Util.*;

    public class Java {

        public static void main(String[] args) {

            String sql = $(
              "Select * from java",
              "join some on ",
              "group by"        
            );

            System.out.println(sql);
        }

    }


    public class Util {

        public static String $(String ...sql){
            return String.join(System.getProperty("line.separator"),sql);
        }

    }
 3
Author: Bruno Marinho,
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-05-18 02:38:15

Cuando se utiliza una serie larga de+, solo se crea un StringBuilder, a menos que la Cadena se determine en tiempo de compilación, en cuyo caso no se utiliza StringBuilder!

El único momento en que StringBuilder es más eficiente es cuando se utilizan varias sentencias para construir la cadena.

String a = "a\n";
String b = "b\n";
String c = "c\n";
String d = "d\n";

String abcd = a + b + c + d;
System.out.println(abcd);

String abcd2 = "a\n" +
        "b\n" +
        "c\n" +
        "d\n";
System.out.println(abcd2);

Nota: Solo se crea un StringBuilder.

  Code:
   0:   ldc     #2; //String a\n
   2:   astore_1
   3:   ldc     #3; //String b\n
   5:   astore_2
   6:   ldc     #4; //String c\n
   8:   astore_3
   9:   ldc     #5; //String d\n
   11:  astore  4
   13:  new     #6; //class java/lang/StringBuilder
   16:  dup
   17:  invokespecial   #7; //Method java/lang/StringBuilder."<init>":()V
   20:  aload_1
   21:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   24:  aload_2
   25:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   28:  aload_3
   29:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   32:  aload   4
   34:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   37:  invokevirtual   #9; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   40:  astore  5
   42:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   45:  aload   5
   47:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   50:  ldc     #12; //String a\nb\nc\nd\n
   52:  astore  6
   54:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   57:  aload   6
   59:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   62:  return

Para aclarar más mi pregunta, no me preocupa en absoluto el rendimiento. Me preocupa el mantenimiento y el diseño cuestión.

Hágalo tan claro y simple como pueda.

 2
Author: Peter Lawrey,
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
2009-05-19 19:39:01

Un pequeño truco. Usando esto inyecto javascartp en una página HTML creada dinámicamente

StringBuilder builder = new StringBuilder();

public String getString()
{
    return builder.toString();
}
private DropdownContent _(String a)
{
    builder.append(a);
    return this;
}

public String funct_showhide()
{
   return
    _("function slidedown_showHide(boxId)").
    _("{").
    _("if(!slidedown_direction[boxId])slidedown_direction[boxId] = 1;").
    _("if(!slideDownInitHeight[boxId])slideDownInitHeight[boxId] = 0;").
    _("if(slideDownInitHeight[boxId]==0)slidedown_direction[boxId]=slidedownSpeed; ").
    _("else slidedown_direction[boxId] = slidedownSpeed*-1;").
    _("slidedownContentBox = document.getElementById(boxId);").
    _("var subDivs = slidedownContentBox.getElementsByTagName('DIV');").
    _("for(var no=0;no<subDivs.length;no++){").
    _(" if(subDivs[no].className=='dhtmlgoodies_content')slidedownContent = subDivs[no];").
    _("}").
    _("contentHeight = slidedownContent.offsetHeight;").
    _("slidedownContentBox.style.visibility='visible';").
    _("slidedownActive = true;").
    _("slidedown_showHide_start(slidedownContentBox,slidedownContent);").
    _("}").getString();

}
 2
Author: Hector Caicedo,
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
2010-12-12 18:39:44

JAVA de último modelo tiene optimizaciones para + con cadenas constantes, emplea un StringBuffer detrás de escena, por lo que no desea saturar su código con él.

Apunta a un descuido de JAVA, que no se parece a ANSI C en la concatenación automática de cadenas entre comillas dobles con solo espacio en blanco entre ellas, por ejemplo:

const char usage = "\n"
"Usage: xxxx <options>\n"
"\n"
"Removes your options as designated by the required parameter <options>,\n"
"which must be one of the following strings:\n"
"  love\n"
"  sex\n"
"  drugs\n"
"  rockandroll\n"
"\n" ;

Me encantaría tener una constante de matriz de caracteres multilínea donde se respeten las semillas de línea incrustadas, para que pueda presentar el bloque sin ningún desorden, por ejemplo:

String Query = "
SELECT
    some_column,
    another column
  FROM
      one_table a
    JOIN
      another_table b
    ON    a.id = b.id
      AND a.role_code = b.role_code
  WHERE a.dept = 'sales'
    AND b.sales_quote > 1000
  Order BY 1, 2
" ;

Para obtener esto, uno necesita vencer a los dioses de JAVA.

 2
Author: David Pickett,
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-04-01 17:40:23

Use Properties.loadFromXML(InputStream). No hay necesidad de libs externas.

Mejor que un código desordenado (ya que la capacidad de mantenimiento y el diseño son su preocupación), es preferible no usar cadenas largas.

Comience leyendo propiedades xml:

 InputStream fileIS = YourClass.class.getResourceAsStream("MultiLine.xml");
 Properties prop = new Properies();
 prop.loadFromXML(fileIS);


entonces puedes usar tu cadena multilínea de una manera más mantenible...

static final String UNIQUE_MEANINGFUL_KEY = "Super Duper UNIQUE Key";
prop.getProperty(UNIQUE_MEANINGFUL_KEY) // "\n    MEGA\n   LONG\n..."


Multilínea.xml ' se encuentra en la misma carpeta YourClass:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

<properties>
    <entry key="Super Duper UNIQUE Key">
       MEGA
       LONG
       MULTILINE
    </entry>
</properties>

PS.: Puedes usar <![CDATA["... "]]> para una cadena similar a xml.

 2
Author: jpfreire,
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-02-26 19:43:19

Sé que esta es una vieja pregunta, sin embargo, para los desarrolladores de intersted, los literales de múltiples líneas estarán en #Java12

Http://mail.openjdk.java.net/pipermail/amber-dev/2018-July/003254.html

 2
Author: Morteza Adi,
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-07-07 22:15:30

Sugiero usar una utilidad como sugiere ThomasP, y luego enlazar eso en su proceso de compilación. Un archivo externo todavía está presente para contener el texto, pero el archivo no se lee en tiempo de ejecución. El flujo de trabajo es entonces:

  1. Construye una utilidad 'textfile to java code' y comprueba el control de versiones
  2. En cada compilación, ejecute la utilidad contra el archivo de recursos para crear una fuente java revisada
  3. El código fuente de Java contiene una cabecera como class TextBlock {... seguido de una cadena estática que es generado automáticamente a partir del archivo de recursos
  4. Construye el archivo java generado con el resto de tu código
 2
Author: horace,
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-07-27 13:02:59