本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
提问:Java多行字符串太丑陋,有什么替代方案吗?
在Java中,当我写一个多行字符串的时候,每一行都必须有繁琐的引号和加号,有什么更好的选择吗?
有人说用StringBuilder.append()
比使用加号更可取,但是我绝对不想用很多方法来拼接字符串,我也不关心性能问题,重要的是可维护性和设计问题。
回答一
我有一个看起来非常牛逼的方法:直接通过注解将多行注释的内容初始化为变量的值。
这是我开源在Github的项目
https://github.com/benelog/multiline
复制代码
下面是实例代码:
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);
}
}
复制代码
这个方案的缺点是:你必须提供相应的注释处理器。该字符串不能定义为局部变量。
该字符串文本有JavaDoc
注释/**
分隔。
你最好还需要对IDE进行设置,防止多行注释被自动格式化。
人们可能会觉得这很奇怪(Javadoc被设计成不会嵌入任何注释以外的东西),但由于Java中缺少多行字符串,我发现这是最优秀的方案。
回答二
听起来你想直接写一个多行文字,但这在Java中是不存在的。你最好的选择是把字符串加在一起。其他人提到了一些其它操作
StringBuilder、String.format、String.join
复制代码
但是这种操作只有使用字符串数组生成字符串时才比较好用。
下面这种使用+
号拼接字符串的方式并不会比使用append()
方法更慢,因为它们是由编译器自动连接,唯一要避免的就是在循环里面用+
号连接字符串。
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()
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"
);
复制代码
对比Java 8 中的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"
);
复制代码
如果想要为特定系统换行,那就需要使用system.LineSeparator()
,也可以使用String.format
中的%n
另一种选择是将资源放在一个txt
文件中,然后读取该文件的内容。对于非常大的字符串,这将是最好的操作,以避免类文件过大。
文章翻译自Stack Overflow:stackoverflow.com/questions/8…