-3

I want to write a method for reading a data from a file in java using ArrayList instead of static String[] array. This is what I wrote so far:

public static ArrayList<String> loadText(String file) {
    ArrayList<String> ret = null;
    BufferedReader in = null;
    String line = null;
        try {
            in = new BufferedReader(new FileReader(file));
            while((line = in.readLine()) != null) {
                ret.add(line);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return ret;
    }

And this is how i called this method in my Test class:

import java.util.ArrayList;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<String> text = Files.loadText("podaci.txt");

        System.out.println(text);
    }
}

There is a problem with:

ret.add(line);

I'm getting NullPointerException, and i can't figure out why...

stevs
  • 9
  • 5

1 Answers1

1

The line

ArrayList<String> ret = null;

sets the variable ret to null. It should not be surprising that the the line

ret.add(line);

throws a NullPointerException.

Consider allocating an ArrayList. Maybe even something like this:

ArrayList ret = new ArrayList();

Edited

DwB
  • 37,124
  • 11
  • 56
  • 82