阅读量:0
在Java中,可以使用以下几种方法读取多行字符串:
- 使用Scanner类读取多行字符串:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); StringBuilder sb = new StringBuilder(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.isEmpty()) { break; } sb.append(line).append("n"); } String multilineString = sb.toString(); System.out.println(multilineString); } }
- 使用BufferedReader类读取多行字符串:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null && line.length() != 0) { sb.append(line).append("n"); } String multilineString = sb.toString(); System.out.println(multilineString); } }
以上是两种常用的方法读取多行字符串,可以根据具体情况选择适合自己的方法。