0

我有一个文件,我们称之为 text.txt。它包含几行文本。我正在尝试用我的代码读入它,以便我可以使用我的代码对其进行编辑,不幸的是,每当我尝试阅读它时,它只会返回 null,并且根本不加载代码。没有错误信息或任何东西。

一个示例是其中包含以下内容的文件:

a
b
c
d
e
f

加载时,它会加载以下内容:

a
b
c
d
null

这对我来说毫无意义,因为如果它正在进入 while 循环,它不应该退出!谁能帮帮我?

try
{
     File theFile = new File(docName);

     if (theFile.exists() && theFile.canRead())
     {  
        BufferedReader docFile;
        docFile = new BufferedReader(
              new FileReader(f));

        String aLine = docFile.readLine();

        while (aLine != null)
        {  
           aLine = docFile.readLine();
           doc.add( aLine );
        }

        docFile.close();
     }
4

4 回答 4

3

请注意,您正在阅读第一行

String aLine = docFile.readLine();

然后你通过做丢弃这条线

aLine = docFile.readLine();

循环内。

于 2011-02-26T20:06:42.453 回答
0
while ( (aLine = docFile.readLine())!= null)
{  
     doc.add( aLine );
}
于 2011-02-26T20:10:30.623 回答
0

在阅读下一行之前添加该行。如果您从逻辑上考虑这一点,它应该是有道理的,如果没有,请询​​问。

于 2011-02-26T20:08:38.800 回答
0

在while循环中,如果你翻转这两个语句,那么它将添加你知道不为空的行,然后检查下一行。你现在拥有它的方式,循环检查该行,然后前进一行并将新行添加到 doc,因此它可以为 null,然后在添加 null 后退出。

于 2011-02-26T20:20:10.890 回答