曾梦垚

导航

ReadLine

//需求:实现通过ReadLine读取代码,每行加上行号

class BufferedReaderLineNum extends BufferedReader{
int count = 1;
//子类继承父类会默认调用父类的无参构造方法
public BufferedReaderLineNum(Reader in){
super(in);
}
//复写readLine方法
public String readLine() throws IOException {
//调用父类的readLine
String content = super.readLine();
if(content == null){
return null;
}
content = count+" "+content;
count++;
return content;
}
}
public class Demo1 {
public static void main(String[] args) throws IOException {
testLineNum();
}

public static void testLineNum() throws IOException{
//1.开启通道,并且带一个文件路径
FileReader reader = new FileReader("C:\\zmy\\test.txt");
//2.创建一个缓冲流,带行号
BufferedReaderLineNum lineNum = new BufferedReaderLineNum(reader);
//3.开始读取数据
String content = null;
while((content = lineNum.readLine()) != null){
System.out.println(content);
}
//4.关闭资源
lineNum.close();
}
}

posted on 2016-12-08 10:55  曾梦垚  阅读(196)  评论(0编辑  收藏  举报