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();
}
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.
Add the line before reading the next line. If you think about this logically, it should make sense, and if not, please ask.
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.
while ( (aLine = docFile.readLine())!= null)
{
doc.add( aLine );
}
精彩评论