import java.io.*;
class MyLineNumberReader
{
//先包装一个Reader,必须要先有流对象,用流对象去读数据,它才能对数据进行行号的添加
private Reader r;
private int lineNumber;
//同时在构造函数中将被包装的对象传进来
MyLineNumberReader(Reader r) //Reader r是被装饰的对象
{
this.r = r;
}
public String myReadLine() throws IOException
{
lineNumber++;//myReadLine方法读一次,行号计数器就会自增一次
StringBuilder sb = new StringBuilder();
int ch = 0;
while((ch=r.read())!=-1)
{
if(ch=='\r')
continue;
if(ch=='\n')
return sb.toString();
else
sb.append((char)ch);
}
if(sb.length()!=0)
return sb.toString();
return null;
}
public void setLineNumber(int lineNumber) throws IOException
{
this.lineNumber = lineNumber;
}
public int getLineNumber()
{
return lineNumber;
}
public void myClose() throws IOException
{
r.close();
}
}
class MyLineNumberReaderDemo
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("PersonDemo.java");
MyLineNumberReader mylnr = new MyLineNumberReader(fr);
String line = null;
while((line=mylnr.myReadLine())!=null)
{
System.out.println(mylnr.getLineNumber()+"::"+line);
}
mylnr.myClose();
}
}