使用BufferedReader显示多行时出现问题

时间:2015-12-02 02:12:21

标签: java bufferedreader

我试图显示多行,但是我得到的只是" null"而不是获得任何输入。

public void display ()
{
    BufferedReader display;
    try
    {
        display = new BufferedReader (new FileReader (fileName));
        while (line != null)
        {
            line = display.readLine ();
        }
        display.close ();
    }
    catch (IOException e)
    {
    }

    c.println (fileName + " display: ");
    c.println (line);
}

1 个答案:

答案 0 :(得分:0)

每次拨打line = display.readLine();时,都会丢弃line的旧值

要获取文件的全部内容,您必须在阅读时保存或打印出来。

要保存它们,请尝试像这样设置内容变量

public void display()
{
    BufferedReader display;
    String contents = "";
    try
    {
        display = new BufferedReader(new FileReader(fileName));
        while(line != null)
        {
            line = display.readLine();
            contents += line + "\n";
        }
        display.close();
    }
    catch(IOException e){}

    c.println(fileName + " display: ");
    c.println(contents);
}

上面的代码将为您提供每行的内容,包括null。您可以使用if语句删除末尾的空值,或稍微更改while循环

我觉得缩小while循环并对每行进行处理更容易

BufferedReader reader = new BufferedReader(new FileReader(filename));
String contents = "";
String line;
while((line = reader.readLine()) != null)
    contents += line + "\n"; //or doStuff(line); if you process data line by line
System.out.println(contents);

比while循环更有意义的是使用for循环

for(String line = reader.readLine(); line != null; line = reader.readLine())
    contents += line + "\n";