Java BufferedReader.readLine() returning null when reading file

I need some help. This is my function:

public String[] getLines(String filename) {
    String[] returnVal = null;
    int i = 0;

    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(filename)));

        for(String line; (line = br.readLine()) != null; ) {
            // process the line.
            returnVal[i] = line;
            i++;
        }

        br.close();
    }
    // Catches any error conditions
    catch (Exception e)
    {
        debug.error("Unable to read file '"+filename+"'");
        debug.message(e.toString());
    }

    return returnVal;
}

which should return me String[] array with all the lines from a specified file. But I only get exception as return:

java.lang.NullPointerException

and when I try to print the result it is null. Any ideas? Thanks!

Answer

You’re setting the value to null explicitly:

String[] returnVal = null;

Since you don’t know how many elements it’ll contain, you should use an ArrayList instead*:

ArrayList<String> returnVal = new ArrayList<>();

* See the API to know what methods you should use to add objects to it

Leave a Reply

Your email address will not be published. Required fields are marked *