本帖最后由 吴扬 于 2012-7-16 15:19 编辑
今天根据视频练习自定义BufferedReader类的时候出现了一个空指针异常,烦请大家帮忙看下
自定义BufferedReader类:- public class MyBufferedReader extends Reader{ //这里继承了Reader类
- private Reader reader;
- public MyBufferedReader(Reader reader) {
- super(reader); //调用了Reader类的构造方法 //解决办法:这里应该改为this.reader = reader;
- }
-
- public String myReadLine() throws IOException
- {
- StringBuilder sb = new StringBuilder();
- int ch = 0;
- while((ch = reader.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 close() throws IOException
- {
- reader.close();
- }
- @Override
- public int read(char[] arg0, int arg1, int arg2) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- }
复制代码 测试类:- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- FileReader fr = new FileReader("d:\\abc.txt");
- MyBufferedReader myBufferedReader = new MyBufferedReader(fr);
-
- String buffer = null;
-
- while((buffer = myBufferedReader.myReadLine()) != null) //这里会报空指针异常
- {
- System.out.println(buffer);
- }
-
- myBufferedReader.myClose();
- }
复制代码 后面经过调试才发现异常产生的原因是继承了Reader类,调用了它的构造方法产生的,但是想了半天也没想明白为什么继承了BufferedReader类就会出现空指针异常,
麻烦各位可以帮我看下吗?谢谢...
|