Java多行字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/878573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java multiline string
提问by skiphoppy
Coming from Perl, I sure am missing the "here-document" means of creating a multi-line string in source code:
来自 Perl,我肯定缺少在源代码中创建多行字符串的“here-document”方法:
$string = <<"EOF" # create a three-line string
text
text
text
EOF
In Java, I have to have cumbersome quotes and plus signs on every line as I concatenate my multiline string from scratch.
在 Java 中,当我从头开始连接多行字符串时,我必须在每一行都有繁琐的引号和加号。
What are some better alternatives? Define my string in a properties file?
有哪些更好的选择?在属性文件中定义我的字符串?
Edit: Two answers say StringBuilder.append() is preferable to the plus notation. Could anyone elaborate as to why they think so? It doesn't look more preferable to me at all. I'm looking for a way around the fact that multiline strings are not a first-class language construct, which means I definitely don't want to replace a first-class language construct (string concatenation with plus) with method calls.
编辑:两个答案说 StringBuilder.append() 比加号更可取。谁能详细说明他们为什么这么认为?它看起来对我来说一点也不可取。我正在寻找一种解决方法,即多行字符串不是一流的语言构造,这意味着我绝对不想用方法调用替换一流的语言构造(带加号的字符串连接)。
Edit: To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.
编辑:为了进一步澄清我的问题,我根本不关心性能。我担心可维护性和设计问题。
采纳答案by Paul Morie
Stephen Colebourne has created a proposalfor adding multi-line strings in Java 7.
Stephen Colebourne提出了在 Java 7 中添加多行字符串的提议。
Also, Groovy already has support for multi-line strings.
此外,Groovy 已经支持多行字符串。
回答by Josh Curren
The only way I know of is to concatenate multiple lines with plus signs
我知道的唯一方法是用加号连接多行
回答by Tom
String newline = System.getProperty ("line.separator");
string1 + newline + string2 + newline + string3
But, the best alternative is to use String.format
但是,最好的选择是使用String.format
String multilineString = String.format("%s\n%s\n%s\n",line1,line2,line3);
回答by Josh Curren
Another option may be to store long strings in an external file and read the file into a string.
另一种选择可能是将长字符串存储在外部文件中并将文件读入字符串。
回答by user54579
You can concatenate your appends in a separate method like:
您可以使用单独的方法连接附加内容,例如:
public static String multilineString(String... lines){
StringBuilder sb = new StringBuilder();
for(String s : lines){
sb.append(s);
sb.append ('\n');
}
return sb.toString();
}
Either way, prefer StringBuilder
to the plus notation.
无论哪种方式,都更喜欢StringBuilder
加号。
回答by Kip
Define my string in a properties file?
在属性文件中定义我的字符串?
Multiline strings aren't allowed in properties files. You can use \n in properties files, but I don't think that is much of a solution in your case.
属性文件中不允许使用多行字符串。您可以在属性文件中使用 \n ,但我认为这不是您的解决方案。
回答by Tom Hawtin - tackline
If you define your strings in a properties file it'll look much worse. IIRC, it'll look like:
如果你在属性文件中定义你的字符串,它看起来会更糟。IIRC,它看起来像:
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:
通常,不将大字符串嵌入到源代码中是一个合理的想法。您可能希望将它们作为资源加载,可能是 XML 或可读的文本格式。文本文件可以在运行时读取或编译为 Java 源代码。如果您最终将它们放在源代码中,我建议将它们放在+
前面并省略不必要的新行:
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"
);
回答by Andreas Dolk
A quite efficient and platform independent solution would be using the system property for line separators and the StringBuilder class to build strings:
一个非常有效且与平台无关的解决方案是使用系统属性作为行分隔符和 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();
回答by Kip
It sounds like you want to do a multiline literal, which does not exist in Java.
听起来您想要执行 Java 中不存在的多行文字。
Your best alternative is going to be strings that are just +
'd together. Some other options people have mentioned (StringBuilder, String.format, String.join) would only be preferable if you started with an array of strings.
您最好的选择是将字符串+
组合在一起。人们提到的其他一些选项(StringBuilder、String.format、String.join)只有在您从字符串数组开始时才更可取。
Consider this:
考虑一下:
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
:
对比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.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()
:
与 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"
);
If you want the newline for your particular system, you either need to use System.lineSeparator()
, or you can use %n
in String.format
.
如果您需要特定系统的换行符,则需要使用System.lineSeparator()
,或者您可以使用%n
in String.format
。
Another option is to put the resource in a text file, and just read the contents of that file. This would be preferable for very large strings to avoid unnecessarily bloating your class files.
另一种选择是将资源放在一个文本文件中,然后读取该文件的内容。这对于非常大的字符串是可取的,以避免不必要地膨胀您的类文件。
回答by Laurence Gonsalves
Sadly, Java does not have multi-line string literals. You either have to concatenate string literals (using + or StringBuilder being the two most common approaches to this) or read the string in from a separate file.
遗憾的是,Java 没有多行字符串文字。您要么必须连接字符串文字(使用 + 或 StringBuilder 是两种最常见的方法),要么从单独的文件中读取字符串。
For large multi-line string literals I'd be inclined to use a separate file and read it in using getResourceAsStream()
(a method of the Class
class). This makes it easy to find the file as you don't have to worry about the current directory versus where your code was installed. It also makes packaging easier, because you can actually store the file in your jar file.
对于大型多行字符串文字,我倾向于使用单独的文件并在 using getResourceAsStream()
(Class
类的方法)中读取它。这使得查找文件变得容易,因为您不必担心当前目录与安装代码的位置。它还使打包更容易,因为您实际上可以将文件存储在 jar 文件中。
Suppose you're in a class called Foo. Just do something like this:
假设您在一个名为 Foo 的类中。只是做这样的事情:
Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);
The one other annoyance is that Java doesn't have a standard "read all of the text from this Reader into a String" method. It's pretty easy to write though:
另一个烦恼是 Java 没有标准的“将来自该 Reader 的所有文本读入字符串”方法。不过写起来很简单:
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();
}