0

我想将文本文件列表读入二维数组。代码在读入数组时引发运行时错误。我怎样才能解决这个问题?

  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();
      }
    }
4

1 回答 1

2

首先

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

最后一条语句将抛出NullPointerException,因为str此时为空。您需要分配数组:

byte[][] str = new byte[2][];
于 2013-03-20T03:23:56.613 回答