Reputation: 3412
I'm trying to read a file line by line, but every time I run my program I get a NullPointerException at the line spaceIndex = line.indexOf(" ");
which obviously means that line is null. HOWEVER. I know for a fact that the file I'm using has exactly 7 lines (even if I print the value of numLines
, I get the value 7. And yet I still get a nullpointerexception when I try to read a line into my string.
// File file = some File I take in after clicking a JButton
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file.toPath(), charset)) {
String line = "";
int spaceIndex;
int numLines = 0;
while(reader.readLine()!=null) numLines++;
for(int i = 0; i<numLines; i++) {
line = reader.readLine();
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
PS: (I'm not actually using this code to print the index of the space, I replaced the code in my loop since there's a lot of it and it would make it longer to read)
If i'm going about reading the lines the wrong way, it would be great if someone could suggest another way, since so far every way I've tried gives me the same exception. Thanks.
Upvotes: 1
Views: 8530
Reputation: 14276
You have two options.
First, you could read number of lines from a file this way:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);
System.out.println(lnr.getLineNumber());
Then read the file right after:
while((line = reader.readLine())!=null)
{
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
This first option is an alternative (and in my my opinion, cooler) way of doing this.
Second option (and probably the more sensible) is to do it all at once in the while loop:
while((line = reader.readLine())!=null)
{
numLines++;
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
Upvotes: 1
Reputation: 887365
By the time you start your for
loop, the reader is already at the end of the file
(from the while
loop).
Therefore, readLine()
will always return null
.
You should get rid of the for
loop and do all of your work in the while
loop as you first read the file.
Upvotes: 5