pranjalshah.ps
pranjalshah.ps

Reputation: 55

Why am I getting a NullPointerException in the following code?

This is code to sort the contents of an existing file:

public void sortFile(String fileName)throws IOException
{
    FileReader fin=new FileReader("C:\\File Handling\\"+fileName+".txt");
    BufferedReader bin=new BufferedReader(fin);

    String[] str=new String[100];

    int i=0;
    while((str[i]=bin.readLine())!=null)
        i++;

    Arrays.sort(str);  //getting a NullPointerException here

    FileWriter fout=new FileWriter("C:\\File Handling\\"+fileName+".txt");
    BufferedWriter bout=new BufferedWriter(fout);
    PrintWriter pout=new PrintWriter(bout);

    for(i=0;i<str.length;i++)
        pout.println(str[i]);
}

However upon executing the code in an IDE, I am getting a java.lang.NullPointerException

Can somebody please tell me why this is happening? I can't figure it out.

Upvotes: 0

Views: 107

Answers (3)

RobMcZag
RobMcZag

Reputation: 645

It is just because you start by declaring a 100 positions array, then you fill JUST some (one per line, until file has lines) and then you scan all the 100 position.

As others already pointed out, first scan is performed by Arrays.sort() calling compare() on null elements when you arrive at a position i where

 str[i] == null 

then you get you error because of calling str[i].compare() on the array item that is null.

To solve the problem you should save the count of how many lines you put in your array and then just sort/loop until that position. BTW you already have it in the i variable when you are reading the file, just store it.

int i=0;
int lineNumber=0;
while((str[i]=bin.readLine())!=null) {
    lineNumber = i++;
}

PS Please use the parenthesis, they will help you a lot in reading and avoiding problems :)

Upvotes: 0

SMA
SMA

Reputation: 37023

You are defining String array with 100 size beforehand, which by default initialized all 100 elements to null. Now if you say have 4 lines in your file, then rest 96 elements would be null and only 4 elements of yours would be initialized. And then when you sort that array you get NullPointerException.

You have two options here:

Either change from String array to List and use api like:

Collections.sort(...);//pass your list

OR Using array you could use api like:

Arrays.sort(String array, startIndex, end Index);

So here you could pass yoru array with 0 as start Index while i as end index. But you are wasting space unnecessarily here.

Upvotes: 0

Toma
Toma

Reputation: 390

You should try:

Arrays.sort(str, 0, i);

The array contains null strings and these cause the NullPointerException.

Upvotes: 6

Related Questions