0

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!

1
  • 1
    returnVal[i] -->returnVal is null. You have to initialize it. Commented Feb 2, 2015 at 14:06

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this helped me! But I wasn't setting the return to null explicitly I just initialized it. But now with the ArrayList it works great :)
1

you have returnVal as null, String[] returnVal = null; and trying to write to it. If you know number of lines in advance, initialize it as returnVal = new String [N_LINES];, and change your loop condition to take into account number lines read. Otherwise you can use a list of strings and append to it as you read:

List<String> returnVal = new ArrayList<>();
...
while((line = br.readLine()) != null) {
    returnVal.add(line);
}

Not related to the original question but still: br.close(); should be in finally and if you're using 1.7, you can benefit from try-with-resources:

List<String> returnVal = new ArrayList<>();
try(BufferedReader br = 
    new BufferedReader(new FileReader(new File(filename)))) {
    while((line = br.readLine()) != null) {
        returnVal.add(line);
    }
} catch (Exception e) {
    debug.error("Unable to read file '"+filename+"'");
    debug.message(e.toString());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.