我想将文本文件列表读入二维数组。该代码在读入数组时抛出运行时错误。我该如何解决这个问题?
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();
}
}
最佳答案
首先
byte[][] str = null;
File file=new File("test1.txt");
str[0]= readFile1(file);
最后一条语句将抛出NullPointerException
,因为此时str
为空。您需要分配数组:
byte[][] str = new byte[2][];
关于java - 将文本文件读入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15514690/