-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 !

  • Take a look at [this](http://stackoverflow.com/questions/1217449/how-can-i-debug-this-nullpointer-exception) and [this](http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx) – isaias-b Jun 23 '14 at 14:17
  • 2
    Please add an error log and tell us which line exactly throws the nullPointerException. – rhbvkleef Jun 23 '14 at 14:17
  • Try researching like I did, http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – Rick S Jun 23 '14 at 14:18
  • Works perfectly for me, tried it on my system, calling `StoreLineByLine(String fileName)` from `main()` . Check your `fileName`. – Mustafa sabir Jun 23 '14 at 14:25
  • Tested on OS X. If `fileName` is NULL, it yields a NPE on that line. See my answer. – Alvin Thompson Jun 23 '14 at 14:57

1 Answers1

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>.

Alvin Thompson
  • 5,388
  • 3
  • 26
  • 39