测试类源码如下:
public class Test {
public static void main(String[] args) {
// 创建字符输入流
BufferedReader bufferedReader = null;
// 创建自定义输入流对象
MyReader myReader = null;
try {
// 封装bufferedReader
bufferedReader = new BufferedReader(new InputStreamReader(
new FileInputStream("Person.java")));
// 实例化MyReader
myReader = new MyReader(bufferedReader);
// 读取数据,输出到控制台
String src = null;
while ((src = myReader.readLine()) != null) {
System.out.println(src);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
封装类源码如下:
package com.itheima;
import java.io.BufferedReader;
import java.io.IOException;
public class MyReader {
// 声明成员bufferedReader变量
private BufferedReader bufferedReader;
// 声明计数器
private int count = 1;
public MyReader(BufferedReader bufferedReader) {
this.bufferedReader = bufferedReader;
}
// 封装readLine()方法
public String readLine() {
StringBuilder builder = new StringBuilder();
try {
String reader = bufferedReader.readLine();
if (reader == null) {
return null;
}
builder.append(count++).append(": ").append(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return builder.toString();
}
}
由于本人技术有限,代码中可能存在不合理的地方,欢迎大家积极点评,
|
|