-4

I'm getting a NullPointerException in java (at this line :FileReader fstream = new FileReader(fileName)) when I try to read a text file line by line and store them in an arraylist with this code :

public ArrayList<String> StoreLineByLine(String fileName) throws IOException {
    String str;

    ArrayList<String> Line = new ArrayList<String>();
    FileReader fstream = new FileReader(fileName);
    BufferedReader myFileReader = new BufferedReader(fstream);

    while ((str = myFileReader.readLine()) != null) {
        Line.add(str);
    }
    myFileReader.close();
    return Line;
}

Could anyone help me understand the problem ? Thanks a lot !

5
  • Take a look at this and this Commented Jun 23, 2014 at 14:17
  • 2
    Please add an error log and tell us which line exactly throws the nullPointerException. Commented Jun 23, 2014 at 14:17
  • Try researching like I did, stackoverflow.com/questions/218384/… Commented Jun 23, 2014 at 14:18
  • Works perfectly for me, tried it on my system, calling StoreLineByLine(String fileName) from main() . Check your fileName. Commented Jun 23, 2014 at 14:25
  • Tested on OS X. If fileName is NULL, it yields a NPE on that line. See my answer. Commented Jun 23, 2014 at 14:57

1 Answer 1

2

If you're getting a NPE on that line, then fileName must be null.

BTW, if you're using JDK 8 then this may be a better way to load the lines. Replace the contents of your method with this:

return Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());

...and change the method's return type from ArrayList<String> to List<String>.

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

7 Comments

Hello, it's the first time I use this website so I don't know how to log the error. The error is on that line : fstream = new FileReader(fileName); I don't understand how come it is null!
Well it still doesn't work :/
whats new issue you are getting?
I still get the NPE error on that line
@user3767791 never pass fileName as null ... have a null check first in the method
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.