我有一个文件,我们称它为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();
     }

最佳答案

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

String aLine = docFile.readLine();


然后通过执行以下操作丢弃此行

aLine = docFile.readLine();


在循环内。

07-24 17:29