说明
可以使用java.io.BufferedReader的readLine()函数读入一行文本,返回的字符串不包含回车和换行字符。
https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/io/BufferedReader.html#readLine()
代码示例
读取控制台的输入
使用下面的代码来验证:
package com.thb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test4 {
public static void main(String[] args) {
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Please input: ");
line = in.readLine();
if (line == null) {
System.out.println("null reference");
}
if (line.equals("")) {
System.out.println("receveid zero-length string");
}
System.out.println("received string: " + line);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}