代码:
import java.io.*;
public class SparseArrToMapdata {
public static void main(String[] args) throws IOException {
int sparseArr[][] = new int [3][3];
sparseArr[0][0] =11;
sparseArr[0][1] =11;
sparseArr[0][2] =2;
sparseArr[1][0] =4;
sparseArr[1][1] =5;
sparseArr[1][2] =1;
sparseArr[2][0] =7;
sparseArr[2][1] =8;
sparseArr[2][2] =0;
File dest = new File("d:\\map.data");
Writer os = null;
os = new FileWriter(dest);
for (int i = 0; i < sparseArr.length; i++) {
for (int j = 0; j < 3; j++) {
os.write(sparseArr[i][j]+"\t");
}
os.write("\r\n");
}
os.close();
File src = new File("d:\\map.data");
BufferedReader in = new BufferedReader(new FileReader(src));
int row =0;
String line;
while ((line = in.readLine()) != null) {
row++;
}
int sparseArr2[][] = new int [row][3];
int rowtmp = 0;
in.close();
in = new BufferedReader(new FileReader(src));
while ((line = in.readLine()) != null) {
String[] temp = line.split("\t");
for (int j = 0; j < temp.length; j++) {
sparseArr2[rowtmp][j]=Integer.parseInt(temp[j]);
}
rowtmp++;
}
in.close();
for(int[]temp1:sparseArr2) {
for (int temp2 : temp1) {
System.out.printf("%d\t", temp2);
}
System.out.println();
}
}
}
注意事项:
- 对于BufferedReader类中的readLine在代码中第一次用的目的是为了得到所需要创建数组的合适大小;
- 遍历完文件的所有行之后,需要进行流的“重启”再次定位到文件第一行,进行遍历,即数据的读取