2 zxy cola zxy_cola 于 2016.03.28 01:13 提问

IO流 自定义readLine 无法读取下一行 5C

import java.io.*;
public class Demo
{
public static void main(String[] args) throws IOException
{
BufferedWriter bfw = new BufferedWriter(new FileWriter("b.txt"));
bfw.write("sdasdaad\r\n");

    bfw.write("1");
    bfw.close();

    myreadline bfr = new myreadline(new FileReader("b.txt"));
    String s = null;
    while((s = bfr.method()) != null)
    {
        sop(s);
    }
    bfr.myclose();

}

public static void sop(Object obj)
{
    System.out.println(obj);
}

}

class myreadline extends Reader
{
private FileReader r ;
myreadline(FileReader r)
{
this.r = r;
}

public String method() throws IOException
{
    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);
    }
    return null;
}

public void myclose()throws IOException
{
    r.close();
}

public void close()throws IOException
{
    r.close();
}

public int read(char[] c , int a , int b) throws IOException
{
    return r.read(c, a , b);
}

}

为什么只能读取一行呢???

1个回答

caozhy
caozhy   Ds   Rxr 2016.03.28 06:12

StringBuilder sb = new StringBuilder();
这个sb放在局部变量里,每次调用都不会再有之前读取的缓冲的字符了。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!