本帖最后由 魏亮 于 2012-11-7 08:03 编辑
import java.io.*;import java.util.*;class MyBufferedReaderDemo { public static void main(String[] args) throws Exception { MyBufferedReader mybufr = new MyBufferedReader(new FileReader("day.txt")); String line=null; while ((line=mybufr.readLine())!=null) { System.out.println(line); } mybufr.myClose(); //System.out.println("Hello World!"); }}可为什么用上面的类调用,老是出错呢,好像打出了很多空字符!!
class MyBufferedReader
{
private Reader r;
MyBufferedReader(Reader r)
{
this.r=r;
}
public String readLine() throws Exception
{
char[] chs = new char[1024];//定义一个数组装数据
int pos=0;
int ch=0;
while ((ch=r.read())!=-1)
{
if (ch=='\r')
{
continue;
}
if (ch=='\n')
{
System.out.println(pos);
//return Arrays.toString(chs);
return new String(chs,0,pos);//将数据返回,pos正好是数组中元素的个数?
}
chs[pos++]=(char)ch;
}
if (chs.length!=0)
{
return new String(chs,0,pos);
}
return null;
}
public void myClose() throws Exception
{
r.close();
}
}
//模拟BufferedReader内部结构, 为什么调用运行上面那个类会打印出一大堆的空字符呢??
//我return的时候明明定义了是0-pos 呀?
|