-2

I am trying to read a file line by line and save it to a byte array, but for some reason String.getBytes() throws a Nullpointer Exception.

What am I doing wrong?

public static void main(String[] args) {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    byte[][] bytes = null;
    try {
        String data;
        int i = 0;
        while((data = br.readLine()) != null) {
            bytes[i] = data.getBytes(); // THROWS A NULLPOINTER EXCEPTION HERE
            i++;
        }
        System.out.println(bytes.length);

    } catch (IOException e)
        e.printStackTrace();
    }

}
YemSalat
  • 19,986
  • 13
  • 44
  • 51

3 Answers3

2

Your byte array bytes is null. Why dont you use an ArrayList?

ArrayList<byte[]> bytes = new ArrayList<>();

And then later in your code:

bytes.add(data.getBytes());
bash0r
  • 774
  • 6
  • 17
  • Thanks, that seems like a better solution. Will I need to declare the type as well? Like so: `ArrayList` ? [EDIT] You edited before I posted - thanks a lot, now its clear. – YemSalat Aug 24 '14 at 23:43
1

The problem is the fact that bytes is null when you try to assign to it (you never instantiated it!). Try this instead:

byte[][] bytes = new bytes[N][];

You have to specify at least the number of rows in the bytes matrix before filling it. I don't know what's supposed to be the value of N, if it's unknown at the start of the loop then we can't use a byte[][] for storing the results - in that case, a variable-length data structure is required, for instance an ArrayList<byte[]> will do the trick:

String data;
List<byte[]> bytes = new ArrayList<byte[]>();
while ((data = br.readLine()) != null) { // we don't need `i` for anything
    bytes.add(data.getBytes());
}
System.out.println(bytes.size());        // this prints the number of rows
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

This is because you never initialized bytes to anyting but null:

 byte[][] bytes = null;
Sean Owen
  • 66,182
  • 23
  • 141
  • 173