来自Perl,我肯定错过了在源代码中创建多行字符串的“here-document”方法:
$string = <<"EOF" # create a three-line string
text
text
text
EOF
在Java中,当我从头开始连接多行字符串时,我必须在每一行上使用繁琐的引号和加号。
有什么更好的选择吗?在属性文件中定义我的字符串?
编辑:有两个答案说StringBuilder.append()比加号更可取。谁能详细解释一下他们为什么这么想?在我看来,这一点也不可取。我正在寻找一种方法来解决多行字符串不是一级语言结构这一事实,这意味着我绝对不想用方法调用取代一级语言结构(字符串连接与加号)。
编辑:为了进一步澄清我的问题,我根本不关心性能。我关心的是可维护性和设计问题。
我有时使用一个并行groovy类来充当一个字符串包
这里的java类
public class Test {
public static void main(String[] args) {
System.out.println(TestStrings.json1);
// consume .. parse json
}
}
以及TestStrings.groovy中令人垂涎的多行字符串
class TestStrings {
public static String json1 = """
{
"name": "Fakeer's Json",
"age":100,
"messages":["msg 1","msg 2","msg 3"]
}""";
}
当然,这只适用于静态字符串。如果我必须在文本中插入变量,我会将整个文件更改为groovy。只要保持强类型实践,它就可以实现。
这个问题有两个答案:
In you want to stick to pure Java, with Java 14 being released in March 2020, you can leverage the JEP 368 - Text Blocks, in Second Preview mode. Actually the feature is in preview mode in other releases (at least 13 has it). I created and example set here.
While this feature is useful, it can be easily abused. Remember that Java requires compilation - having large character arrays in your code can be an easy way to shoot yourself in the leg (if you want a quick change, you will need recompilation - that toolset might not be available to the guy operating your application).
根据我的经验,建议在配置文件中保留大字符串(通常是应用程序操作员可以/应该在运行时更改的字符串)。
总结:负责地使用文本块:)。
这是一个老线程,但是一个新的非常优雅的解决方案(只有4个或3个小缺点)是使用自定义注释。
查询:http://www.adrianwalker.org/2011/12/java-multiline-string.html
受此启发的一个项目托管在GitHub上:
https://github.com/benelog/multiline
Java代码示例:
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);
}
}
缺点是
您必须激活相应的(提供的)注释
处理器。
该字符串变量不能定义为局部变量检查原始字符串字面量项目,其中您可以将变量定义为局部变量
字符串不能像在Visual Basic .Net中那样包含其他变量
使用XML文本(<%=变量%>):-)
字符串文字由JavaDoc注释(/**)分隔
而且您可能必须配置Eclipse/Intellij-Idea,使其不会自动重新格式化Javadoc注释。
有人可能会觉得这很奇怪(Javadoc注释并不是为嵌入注释以外的任何内容而设计的),但由于Java中缺少多行字符串确实令人讨厌,因此我认为这是最不糟糕的解决方案。
当我读到多行语法确实是为jdk7计划的(在java存在了多少年之后?)时,我有点恼火。有趣的是,甚至还没有readAll()函数用于读取文件的完整内容(仅从jdk7读取,啊啊),因此下面的代码读取单行。
/*
MakeMultiline v1.0 (2010) - Free to use and copy.
Small gadget to turn text blobs into one java string literal
(doing the split in lines, adding \n at each end and enclosing
in double quotes). Does escape quotes encountered in the text blob.
Useful for working around missing multiline string syntax in java
prior jdk7. Use with:
java MakeMultiline " "
or
java MakeMultiline " " mytextfile.txt
*/
import java.io.*;
class MakeMultiline {
public static void main(String[] args) {
try {
// args[0]: indent
// args[1]: filename to read (optional; stdin if not given)
// Beware the nmb of newlines at the end when using stdin!
String indent = (args.length > 0 ? args[0] : "");
FileReader fr = null; BufferedReader br;
if (args.length > 1)
{ fr = new FileReader(args[1]); br = new BufferedReader(fr); }
else
{ br = new BufferedReader(new InputStreamReader(System.in)); }
String s; String res = "";
while((s = br.readLine()) != null) {
if (res.length() > 0) res += " +\n";
res += indent + "\"" + s.replace("\"", "\\\"") + "\\n\"";
}
br.close(); if (fr != null) fr.close();
System.out.println(res + ";");
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
这对我来说是最快的解决办法。(2010-01-27)