方式1

1
2
3
4
5
String s = "床前明月光,\n" +
"疑是地上霜。\n" +
"举头望明月,\n" +
"低头思故乡。";
System.out.println(s);

方式2

1
2
3
4
5
6
StringBuilder sb = new StringBuilder();
sb.append("床前明月光,\n");
sb.append("疑是地上霜。\n");
sb.append("举头望明月,\n");
sb.append("低头思故乡。");
System.out.println(sb.toString());

或者:

1
2
3
4
5
6
StringBuilder sb = new StringBuilder();
sb.append("床前明月光,\n")
.append("疑是地上霜。\n")
.append("举头望明月,\n")
.append("低头思故乡。");
System.out.println(sb.toString());

方式3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public static String join(String delimiter, String ...elements) {
if (elements.length == 0) {
return null;
} else if (elements.length == 1) {
return elements[0];
} else {
StringBuilder sb = new StringBuilder(1024);
for (int i=0; i < elements.length; ++i) {
if (i < elements.length-1) {
sb.append(elements[i]).append(delimiter);
} else {
sb.append(elements[i]);
}

}
return sb.toString();
}
}

public static String multiLines(String ...lines) {
return join("\n", lines);
}

@Test
public void test() {
String s = multiLines(
"床前明月光,",
"疑是地上霜。",
"举头望明月,",
"低头思故乡。"
);
System.out.println(s);
}

方式4

将文本写入src/main/resources/constant/jingyesi.txt

1
2
3
4
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public String readResource(String path) throws IOException {

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

// 符合要求的文件可能不止一个
Enumeration<URL> configs = ClassLoader.getSystemResources(path);

List<URL> urlList = new ArrayList<>();

while(configs.hasMoreElements()) {
URL url = configs.nextElement();
urlList.add(url);
}
if (urlList.size() != 1) {
throw new IOException("文件不存在,或者存在重复文件");
}

InputStream in = urlList.get(0).openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));

StringBuilder sb = new StringBuilder();
while(true) {
String line = reader.readLine();
if (line != null) {
sb.append(line).append("\n");
} else {
break;
}
}

return sb.toString();
}

@Test
public void test() throws IOException {
System.out.println(readResource("constant/jingyesi.txt"));
}