使用RandomAccessFile先读取一次计算行数,seek重置到文件头部,再读取每行,赋值给a数组。
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test {
//此题目关键是根据文件内容确定二维数组的行数和列数
public static void main(String[] args) {
RandomAccessFile reader = null;
try {
reader = new RandomAccessFile("test.txt", "r");
int n = 0;//行数
while (reader.readLine() != null) {//第一次按行读取只为了计算行数
n++;
}
String[][] a = new String[n][];
reader.seek(0);//重置到文件头部
int j;
String line;
String[] strs;
int i=0;
while ((line = reader.readLine()) != null) {//第二次按行读取是真正的读取数据
strs = line.split(" ");//把读取到的一行数据以空格分割成子字符串数组
a[i]=new String[strs.length];//列数就是数组strs的大小,此句是逐行创建二维数组的列
for (j = 0; j < strs.length; j++) {
a[i][j] = strs[j];//逐行给二维数组的每一列赋值
}
i++;
}
for (i = 0; i < n; i++) {
for (j = 0; j < a[i].length; j++) {
System.out.println("a[" + i + "][" + j + "]=" + a[i][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果如图
