Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java多行字符串_Java_String_Multiline - Fatal编程技术网

Java多行字符串

Java多行字符串,java,string,multiline,Java,String,Multiline,来自Perl,我肯定缺少在源代码中创建多行字符串的“here document”方法: $string = <<"EOF" # create a three-line string text text text EOF $string= 但是,最好的选择是使用 另一种选择可能是将长字符串存储在外部文件中,并将文件读入字符串。您可以使用单独的方法连接附录,如: public static String multilineString(String... lines){ Str

来自Perl,我肯定缺少在源代码中创建多行字符串的“here document”方法:

$string = <<"EOF"  # create a three-line string
text
text
text
EOF
$string=
但是,最好的选择是使用


另一种选择可能是将长字符串存储在外部文件中,并将文件读入字符串。

您可以使用单独的方法连接附录,如:

public static String multilineString(String... lines){
   StringBuilder sb = new StringBuilder();
   for(String s : lines){
     sb.append(s);
     sb.append ('\n');
   }
   return sb.toString();
}
无论哪种方式,都首选
StringBuilder
而不是加号符号

在属性文件中定义我的字符串


属性文件中不允许使用多行字符串。您可以在属性文件中使用\n,但我认为这在您的情况下不是一个很好的解决方案。

如果在属性文件中定义字符串,情况会更糟。IIRC,它看起来像:

string:text\u000atext\u000atext\u000a
一般来说,不在源代码中嵌入大字符串是一个合理的想法。您可能希望将它们作为资源加载,可能是XML或可读文本格式。文本文件可以在运行时读取,也可以编译成Java源代码。如果最终将它们放在源代码中,我建议将
+
放在前面,并省略不必要的新行:

final String text = ""
    +"text "
    +"text "
    +"text"
;
如果有新行,可能需要一些连接或格式化方法:

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

一个非常高效且独立于平台的解决方案是使用行分隔符的system属性和StringBuilder类来构建字符串:

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();
String separator=System.getProperty(“line.separator”);
字符串[]行={“第1行”,“第2行”/*,…*/};
StringBuilder=新的StringBuilder(行[0]);
对于(int i=1;i
听起来像是要执行Java中不存在的多行文字

最好的选择是将
+
'组合在一起的字符串。人们提到的其他一些选项(StringBuilder、String.format、String.join)只有在从字符串数组开始时才更可取

考虑这一点:

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";
与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();
String.format()
相比:

与Java8相比:

如果要为特定系统使用换行符,则需要使用
system.lineSeparator()
,或者可以在
String.format
中使用
%n


另一种选择是将资源放在文本文件中,然后只读取该文件的内容。这对于非常大的字符串来说更可取,以避免不必要地膨胀类文件。

遗憾的是,Java没有多行字符串文本。您必须连接字符串文字(使用+或StringBuilder是两种最常用的方法),或者从单独的文件中读入字符串

对于大型多行字符串文本,我倾向于使用一个单独的文件,并使用
getResourceAsStream()
(类的一种方法)读取它。这使得查找文件变得很容易,因为您不必担心当前目录与代码的安装位置。它还使打包更容易,因为您实际上可以将文件存储在jar文件中

假设你在一个叫做Foo的班上。就这样做吧:

Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);
entityManager.persist(
    new Book()
    .setId(1L)
    .setIsbn("978-9730228236")
    .setProperties("""
        {
           "title": "High-Performance Java Persistence",
           "author": "Vlad Mihalcea",
           "publisher": "Amazon",
           "price": 44.99,
           "reviews": [
               {
                   "reviewer": "Cristiano",
                   "review": "Excellent book to understand Java Persistence",
                   "date": "2017-11-14",
                   "rating": 5
               },
               {
                   "reviewer": "T.W",
                   "review": "The best JPA ORM book out there",
                   "date": "2019-01-27",
                   "rating": 5
               },
               {
                   "reviewer": "Shaikh",
                   "review": "The most informative book",
                   "date": "2016-12-24",
                   "rating": 4
               }
           ]
        }
        """
    )
);
另一个烦恼是Java没有一个标准的“将此读取器中的所有文本读入字符串”方法。不过写起来很容易:

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();
}

Stephen Colebourne创建了一个用于在Java7中添加多行字符串的方法


此外,Groovy已经支持。

plus被转换为StringBuilder.append,除非这两个字符串都是常量,以便编译器可以在编译时组合它们。至少,在Sun的编译器中是这样的,我怀疑大多数(如果不是所有的话)其他编译器也会这样做

因此:

通常生成与以下代码完全相同的代码:

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

String c="Hello"+"Goodbye";
同:

String c="HelloGoodbye";

也就是说,在多行中使用加号打断字符串文字的可读性是没有任何惩罚的。

如果不考虑它的作用,就永远不要使用它。但对于一次性脚本,我已经非常成功地使用了它:

例如:

    System.out.println(S(/*
This is a CRAZY " ' ' " multiline string with all sorts of strange 
   characters!
*/));
 String s1 = """
 text
 text
 text
 """;
代码:


另一个我还没有看到的答案是


还有一个事实是它有一个
newLine()
方法。

我建议使用ThomasP建议的实用程序,然后将其链接到构建过程中。仍然存在包含文本的外部文件,但在运行时不会读取该文件。 工作流程如下:

  • 构建一个“textfiletojava代码”实用程序并签入版本控制
  • 在每个构建中,针对资源文件运行该实用程序,以创建修订的java源代码
  • Java源代码包含一个类似
    class TextBlock{…
    后跟从资源文件自动生成的静态字符串
  • 用剩下的代码构建生成的java文件

  • 您可以使用scala代码,该代码与java兼容,并允许多行字符串用“”括起来:

    package foobar
    对象SWrap{
    def bar=“”约翰说:“这是
    测验
    血淋淋的考验,,
    “亲爱的。”然后关上门
    }
    
    (注意字符串中的引号)和来自java的:

    String s2 = foobar.SWrap.bar ();
    
    这是否更舒适

    如果您经常处理长文本(应该放在源代码中),另一种方法可能是脚本,它从外部文件获取文本,并将其包装为多行java字符串,如下所示:

    sed '1s/^/String s = \"/;2,$s/^/\t+ "/;2,$s/$/"/' file > file.java
    
    因此,您可以轻松地将其剪切并粘贴到源代码中。

    由于Java本机不支持多行字符串,目前唯一的方法是使用上述技术之一对其进行破解。我使用上面提到的一些技巧构建了以下Python脚本:

    import sys
    import string
    import os
    
    print 'new String('
    for line in sys.stdin:
        one = string.replace(line, '"', '\\"').rstrip(os.linesep)
        print '  + "' + one + ' "'
    print ')'
    
    将其放入名为javastringify.py的文件中,并将字符串放入mystring.txt文件中,然后按如下方式运行它:

    cat mystring.txt | python javastringify.py
    
    List<Tuple> posts = entityManager
    .createNativeQuery("""
        SELECT *
        FROM (
            SELECT *,
                   dense_rank() OVER (
                       ORDER BY "p.created_on", "p.id"
                   ) rank
            FROM (
                SELECT p.id AS "p.id",
                       p.created_on AS "p.created_on",
                       p.title AS "p.title",
                       pc.id as "pc.id",
                       pc.created_on AS "pc.created_on",
                       pc.review AS "pc.review",
                       pc.post_id AS "pc.post_id"
                FROM post p
                LEFT JOIN post_comment pc ON p.id = pc.post_id
                WHERE p.title LIKE :titlePattern
                ORDER BY p.created_on
            ) p_pc
        ) p_pc_r
        WHERE p_pc_r.rank <= :rank
        """,
        Tuple.class)
    .setParameter("titlePattern", "High-Performance Java Persistence %")
    .setParameter("rank", 5)
    .getResultList();
    
    然后可以复制输出并将其粘贴到编辑器中

    根据需要对其进行修改,以
    String s2 = foobar.SWrap.bar ();
    
    sed '1s/^/String s = \"/;2,$s/^/\t+ "/;2,$s/$/"/' file > file.java
    
    import sys
    import string
    import os
    
    print 'new String('
    for line in sys.stdin:
        one = string.replace(line, '"', '\\"').rstrip(os.linesep)
        print '  + "' + one + ' "'
    print ')'
    
    cat mystring.txt | python javastringify.py
    
    String str = "paste your text here";
    
    String out = Joiner.on(newline).join(ImmutableList.of(
        "line1",
        "line2",
        "line3"));
    
    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);
      }
    }
    
     InputStream fileIS = YourClass.class.getResourceAsStream("MultiLine.xml");
     Properties prop = new Properies();
     prop.loadFromXML(fileIS);
    
    static final String UNIQUE_MEANINGFUL_KEY = "Super Duper UNIQUE Key";
    prop.getProperty(UNIQUE_MEANINGFUL_KEY) // "\n    MEGA\n   LONG\n..."
    
    <?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>
    
        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");
    
    /**
      <html>
        <head/>
        <body>
          <p>
            Hello<br/>
            Multiline<br/>
            World<br/>
          </p>
        </body>
      </html>
      */
      @Multiline
      private static String html;
    
    String s = String.join(
        System.getProperty("line.separator"),
        "First line.",
        "Second line.",
        "The rest.",
        "And the last!"
    );
    
    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);
            }
    
        }
    
    ""
    
    String multiLine = `First line
        Second line with indentation
    Third line
    and so on...`; // the formatting as desired
    System.out.println(multiLine);
    
    First line
        Second line with indentation
    Third line
    and so on...
    
     String s1 = """
     text
     text
     text
     """;
    
    List<Tuple> posts = entityManager
    .createNativeQuery(
        "SELECT *\n" +
        "FROM (\n" +
        "    SELECT *,\n" +
        "           dense_rank() OVER (\n" +
        "               ORDER BY \"p.created_on\", \"p.id\"\n" +
        "           ) rank\n" +
        "    FROM (\n" +
        "        SELECT p.id AS \"p.id\",\n" +
        "               p.created_on AS \"p.created_on\",\n" +
        "               p.title AS \"p.title\",\n" +
        "               pc.id as \"pc.id\",\n" +
        "               pc.created_on AS \"pc.created_on\",\n" +
        "               pc.review AS \"pc.review\",\n" +
        "               pc.post_id AS \"pc.post_id\"\n" +
        "        FROM post p\n" +
        "        LEFT JOIN post_comment pc ON p.id = pc.post_id\n" +
        "        WHERE p.title LIKE :titlePattern\n" +
        "        ORDER BY p.created_on\n" +
        "    ) p_pc\n" +
        ") p_pc_r\n" +
        "WHERE p_pc_r.rank <= :rank\n",
        Tuple.class)
    .setParameter("titlePattern", "High-Performance Java Persistence %")
    .setParameter("rank", 5)
    .getResultList();
    
    List<Tuple> posts = entityManager
    .createNativeQuery("""
        SELECT *
        FROM (
            SELECT *,
                   dense_rank() OVER (
                       ORDER BY "p.created_on", "p.id"
                   ) rank
            FROM (
                SELECT p.id AS "p.id",
                       p.created_on AS "p.created_on",
                       p.title AS "p.title",
                       pc.id as "pc.id",
                       pc.created_on AS "pc.created_on",
                       pc.review AS "pc.review",
                       pc.post_id AS "pc.post_id"
                FROM post p
                LEFT JOIN post_comment pc ON p.id = pc.post_id
                WHERE p.title LIKE :titlePattern
                ORDER BY p.created_on
            ) p_pc
        ) p_pc_r
        WHERE p_pc_r.rank <= :rank
        """,
        Tuple.class)
    .setParameter("titlePattern", "High-Performance Java Persistence %")
    .setParameter("rank", 5)
    .getResultList();
    
    entityManager.persist(
        new Book()
        .setId(1L)
        .setIsbn("978-9730228236")
        .setProperties(
            "{" +
            "   \"title\": \"High-Performance Java Persistence\"," +
            "   \"author\": \"Vlad Mihalcea\"," +
            "   \"publisher\": \"Amazon\"," +
            "   \"price\": 44.99," +
            "   \"reviews\": [" +
            "       {" +
            "           \"reviewer\": \"Cristiano\", " +
            "           \"review\": \"Excellent book to understand Java Persistence\", " +
            "           \"date\": \"2017-11-14\", " +
            "           \"rating\": 5" +
            "       }," +
            "       {" +
            "           \"reviewer\": \"T.W\", " +
            "           \"review\": \"The best JPA ORM book out there\", " +
            "           \"date\": \"2019-01-27\", " +
            "           \"rating\": 5" +
            "       }," +
            "       {" +
            "           \"reviewer\": \"Shaikh\", " +
            "           \"review\": \"The most informative book\", " +
            "           \"date\": \"2016-12-24\", " +
            "           \"rating\": 4" +
            "       }" +
            "   ]" +
            "}"
        )
    );
    
    entityManager.persist(
        new Book()
        .setId(1L)
        .setIsbn("978-9730228236")
        .setProperties("""
            {
               "title": "High-Performance Java Persistence",
               "author": "Vlad Mihalcea",
               "publisher": "Amazon",
               "price": 44.99,
               "reviews": [
                   {
                       "reviewer": "Cristiano",
                       "review": "Excellent book to understand Java Persistence",
                       "date": "2017-11-14",
                       "rating": 5
                   },
                   {
                       "reviewer": "T.W",
                       "review": "The best JPA ORM book out there",
                       "date": "2019-01-27",
                       "rating": 5
                   },
                   {
                       "reviewer": "Shaikh",
                       "review": "The most informative book",
                       "date": "2016-12-24",
                       "rating": 4
                   }
               ]
            }
            """
        )
    );