下面是毕老师在讲IO关于自己写readLine()的课堂例子,我按老师的思路自己写了遍代码,编译能通过,但执行时却报错,
Exception in thread "main" java.lang.NullPointerException
at myBuffered.myReadLine(myBuffered.java:21)
at myBufferedDemo.main(myBuffered.java:39)
空指针异常,但我的代码和老师课堂上的一样,老师能通过每报错的。我把StringBuilder sb=null;注释掉后,重写,运行通过。问题是为什么呢?
import java.io.*;
class myBuffered
{
private FileReader r;
myBuffered(FileReader r)
{
this.r=r;
}
public static String myReadLine(FileReader r)throws IOException
{
int ch;
//StringBuilder sb=null;
StringBuilder sb=new StringBuilder();
while((ch=r.read())!=-1)
{
if(ch=='\r')
continue;
if(ch=='\n')
return sb.toString();
else sb.append((char)ch);
}
return null;
}
public void myClose()throws IOException
{
r.close();
}
}
class myBufferedDemo
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("copyDemo.java");
String line=null;
while((line=myBuffered.myReadLine(fr))!=null)
{
System.out.println(line);
//fr.newLine();
}
fr.close();
}
}
|
|