Java multiline string

前端 未结 30 2931
醉梦人生
醉梦人生 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:21

    If you define your strings in a properties file it'll look much worse. IIRC, it'll look like:

    string:text\u000atext\u000atext\u000a
    

    Generally it's a reasonable idea to not embed large strings in to source. You might want to load them as resources, perhaps in XML or a readable text format. The text files can be either read at runtime or compiled into Java source. If you end up placing them in the source, I suggest putting the + at the front and omitting unnecessary new lines:

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

    If you do have new lines, you might want some of join or formatting method:

    final String text = join("\r\n"
        ,"text"
        ,"text"
        ,"text"
    );
    

提交回复
热议问题