Java 中的 BufferedReader 类。
java 8object oriented programmingprogramming更新于 2025/11/20 7:40:17
Java 的 BufferedReader 类用于从指定源(字符输入流)读取字符流。此类的构造函数接受 InputStream 对象作为参数。
此类提供名为 read() 和 readLine() 的方法,分别从源读取并返回字符和下一行并返回它们。
实例化 InputStreamReader 类,绕过 InputStream 对象作为参数。
然后,创建一个 BufferedReader,绕过上面获得的 InputStreamReader 对象作为参数。
现在,使用 readLine() 或 read() 方法从当前读取器读取数据作为字符串。
示例
以下 Java 程序演示如何使用 BufferedReader 类从用户读取整数数据。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Employee{
String name;
int id;
int age;
Employee(String name, int age, int id){
this.name = name;
this.age = age;
this.id = id;
}
public void displayDetails(){
System.out.println("姓名: "+this.name);
System.out.println("年龄: "+this.age);
System.out.println("ID: "+this.id);
}
}
public class ReadData {
public static void main(String args[]) throws IOException {
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入您的姓名: ");
String name = reader.readLine();
System.out.println("请输入您的年龄:");
int age = Integer.parseInt(reader.readLine());
System.out.println("请输入您的 ID:");
int id = Integer.parseInt(reader.readLine());
Employee std = new Employee(name, age, id);
std.displayDetails();
}
}
输出
输入您的姓名: Krishna 输入您的年龄: 25 输入您的 ID: 1233 姓名:Krishna 年龄:25 ID:1233

