本帖最后由 黑马连家华 于 2012-8-13 17:27 编辑
/*
自定义一个缓冲区,可以输出行号
*/
import java.io.*;
class MyBufferedReader
{
private FileReader fr;
private int num;
MyBufferedReader(FileReader fr)
{
this.fr = fr;
}
public void mySetLineNumber(int num)
{
//this.num = num+1;改成
this.num=num;
}
public int myGetLineNumber()
{
//return num++;改成
return num;
}
public String myReadLine() throws IOException
{
num++;
BufferedReader br = new BufferedReader(fr);
return br.readLine();
}
public void myClose() throws IOException
{
fr.close();
}
}
class ReadBufferDemoWithLineNumber
{
public static void main(String[] args)
{
MyBufferedReader mbr = null;
try
{
mbr = new MyBufferedReader(new FileReader("BufferedWriterDemo.java"));
mbr.mySetLineNumber(100);
String buffer = null;
while ((buffer = mbr.myReadLine()) != null)
{
System.out.println(mbr.myGetLineNumber()+" : "+buffer);
}
}
catch (IOException e)
{
throw new RuntimeException("读取错误");
}
finally
{
try
{
if (mbr != null)
{
mbr.myClose();
}
}
catch (IOException e)
{
throw new RuntimeException("无法关闭流资源");
}
}
}
}
打印结果是
101 : /*
不知道哪里出错了?
原来后面有答案呀...太性急了..
等我看完,还不会的话再来看看大家的答案
虽然上面的代码还不对,但我已经会了,谢谢楼下的兄弟哦 |