0

I want to read a list of text files into a 2D array. The code throws a run time error on reading into the array. How can I fix this?

  public static void main(String[] args) throws IOException
   {    
   byte[][] str = null;
   File file=new File("test1.txt");
   str[0]= readFile1(file);

   File file2=new File("test2.txt");
   str[1]= readFile1(file2);
  }

 public static byte[] readFile1 (File file) throws IOException {

    RandomAccessFile f = new RandomAccessFile(file, "r");

    try {    
        long longlength = f.length();
        int length = (int) longlength;
        if (length != longlength) throw new IOException("File size >= 2 GB");

        byte[] data = new byte[length];
        f.readFully(data);
        return data;
    }
    finally {
        f.close();
      }
    }
user2002858
  • 341
  • 2
  • 7
  • 18
  • 1
    **What does the error say**? – SLaks Mar 20 '13 at 03:21
  • 1) *"throws a run time error"* Narrow it down by copy/pasting the stack trace as an [edit to the question](http://stackoverflow.com/posts/15514690/edit). 2) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Mar 20 '13 at 03:21

1 Answers1

2

To begin with

byte[][] str = null;
File file=new File("test1.txt");
str[0]= readFile1(file);

the last statement will throw NullPointerException since str is null at this point. You need to allocate the array:

byte[][] str = new byte[2][];
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190