Java multiline string

前端 未结 30 2627
醉梦人生
醉梦人生 2020-11-22 15:55

Coming from Perl, I sure am missing the \"here-document\" means of creating a multi-line string in source code:

$string = <<\"EOF\"  # create a three-l         


        
相关标签:
30条回答
  • 2020-11-22 16:26

    This is an old thread, but a new quite elegant solution (with only 4 maybe 3 little drawbacks) is to use a custom annotation.

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

    A project inspired from that work is hosted on GitHub:

    https://github.com/benelog/multiline

    Example of Java code:

    import org.adrianwalker.multilinestring.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);
      }
    }
    

    The drawbacks are

    1. that you have to activate the corresponding (provided) annotation processor.
    2. that String variable can not be defined as local variable Check Raw String Literals project where you can define variables as local variables
    3. that String cannot contains other variables as in Visual Basic .Net with XML literal (<%= variable %>) :-)
    4. that String literal is delimited by JavaDoc comment (/**)

    And you probably have to configure Eclipse/Intellij-Idea to not reformat automatically your Javadoc comments.

    One may find this weird (Javadoc comments are not designed to embed anything other than comments), but as this lack of multiline string in Java is really annoying in the end, I find this to be the least worst solution.

    0 讨论(0)
  • 2020-11-22 16:27

    Pluses are converted to StringBuilder.append, except when both strings are constants so the compiler can combine them at compile time. At least, that's how it is in Sun's compiler, and I would suspect most if not all other compilers would do the same.

    So:

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

    normally generates exactly the same code as:

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

    On the other hand:

    String c="Hello"+"Goodbye";
    

    is the same as:

    String c="HelloGoodbye";
    

    That is, there's no penalty in breaking your string literals across multiple lines with plus signs for readability.

    0 讨论(0)
  • 2020-11-22 16:28

    Java 13 preview:

    Text Blocks Come to Java. Java 13 delivers long-awaited multiline string by Mala Gupta

    With text blocks, Java 13 is making it easier for you to work with multiline string literals. You no longer need to escape the special characters in string literals or use concatenation operators for values that span multiple lines.

    Text block is defined using three double quotes (""") as the opening and closing delimiters. The opening delimiter can be followed by zero or more white spaces and a line terminator.

    Example:

     String s1 = """
     text
     text
     text
     """;
    
    0 讨论(0)
  • 2020-11-22 16:30

    In Eclipse if you turn on the option "Escape text when pasting into a string literal" (in Preferences > Java > Editor > Typing) and paste a multi-lined string whithin quotes, it will automatically add " and \n" + for all your lines.

    String str = "paste your text here";
    
    0 讨论(0)
  • 2020-11-22 16:30

    With JDK/12 early access build # 12, one can now use multiline strings in Java as follows :

    String multiLine = `First line
        Second line with indentation
    Third line
    and so on...`; // the formatting as desired
    System.out.println(multiLine);
    

    and this results in the following output:

    First line
        Second line with indentation
    Third line
    and so on...
    

    Edit: Postponed to java 13

    0 讨论(0)
  • 2020-11-22 16:30

    One good option.

    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);
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题