硬盘读取还原稀疏数组的一个解决方案

还原二维数组的稀疏数组的时候,需要确定稀疏数组的行数。对于这种稀疏数组,列数总是3。

11  11   2

1    2   1

2   3   2

对于上面这个稀疏数组,右上角的2代表了二维数组中的非0元素个数,第一行的两个11代表二维数组为11乘11的数组。问题的关键在于提取右上角的数字,把这个数字加1,就可以确定稀疏数组的行数了。

利用以下代码可以完成稀疏数组的初始化:

1 FileReader fr1 = null;
2 BufferedReader br = null;
3 File file1 = new File("SparseArray.txt");
4 fr1 = new FileReader(file1);
5 br = new BufferedReader(fr1);
6 String firstLine = br.readLine();
7 String[] headSplits = firstLine.split("\t");
8 int i1 = Integer.parseInt(headSplits[2]);
9 int[][] arr = new int[i1 + 1][3];

但是如果接下来直接进行操作数组的读取操作就会出现问题:

1 String line;
2 int row = 0;
3 while ((line = br.readLine()) != null) {
4     String[] temp = line.split("\t");
5     for (int i = 0; i < temp.length; i++) {
6         arr[row][i] = Integer.parseInt(temp[i]);
7     }
8     row++;
9 }

原因在于readLine()方法是自动迭代的,其指针在第一个代码块那里读取了第一行数据以后就自动下移到第二行,最终使读出的稀疏矩阵不含第一行的数据。

解决方案可以利用BufferedReader类下的mark()和reset()方法,将指针手动重新定位:

File file1 = new File("SparseArray.txt");
fr1
= new FileReader(file1); br = new BufferedReader(fr1); br.mark(2); String firstLine = br.readLine(); String[] headSplits = firstLine.split("\t"); int i1 = Integer.parseInt(headSplits[2]); int[][] arr = new int[i1 + 1][3]; br.reset();//让readLine的指针回到起点处

需要注意的是在缓冲流下br.mark()方法内的形参,代表标记之后可以读取的最大字节数,并不具有绝对意义,有时候超出这个限制也是可以正常工作的。

posted @ 2021-04-13 17:02  imissinstagram  Views(69)  Comments(0)    收藏  举报