steveom
steveom

Reputation: 37

Java reading from file problem

I have a file, let's call it text.txt. It contains a few lines of text. I am trying to read this in with my code so that I can edit it using my code, unfortunately whenever I try and read it, it simply returns null, and does not load the code at all. No error message or anything.

An example is a file with the following in it :

a
b
c
d
e
f

when loaded, it loads the following :

a
b
c
d
null

Which makes no sense to me whatsoever, since, if it is entering the while loop, it shouldn't be exiting! Can anyone help me out please ?

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();
     }

Upvotes: 0

Views: 408

Answers (4)

Dead Programmer
Dead Programmer

Reputation: 12585

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

Upvotes: 0

MikeH
MikeH

Reputation: 138

In the while loop, if you flip the two statements, then it will add the line you know is not null, then check the next line. The way you have it now, the loop checks the line, then advances a line and adds the new one to doc, so it can be null, then exit after adding null.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

Add the line before reading the next line. If you think about this logically, it should make sense, and if not, please ask.

Upvotes: 0

Jong Bor Lee
Jong Bor Lee

Reputation: 3855

Note that you are reading the first line with

String aLine = docFile.readLine();

and then you discard this line by doing

aLine = docFile.readLine();

inside the loop.

Upvotes: 3

Related Questions