我想将文本文件列表读入2D数组。代码在读入数组时会引发运行时错误。我该如何解决这个问题?
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();
}
}
答案 0 :(得分:2)
首先
byte[][] str = null;
File file=new File("test1.txt");
str[0]= readFile1(file);
最后一个语句将抛出NullPointerException
,因为str
此时为空。您需要分配数组:
byte[][] str = new byte[2][];