public static void main(String[] args){
int array1[][] = new int[11][11];
array1[1][5] = 1;
array1[2][6] = 2;
int sum = 0;
for(int i=0;i<11;i++) {
for(int j=0;j<11;j++) {
System.out.printf("%d\t",array1[i][j]);
if(array1[i][j] > 0) {
sum+=1;
}
}
System.out.println();
}
/*
* for(int[] i:array1 ) { for(int j:i) { System.out.printf("%d\t",j); }
* System.out.println(); }
*/
//转成稀疏数组
int sparseArray[][] = new int[sum+1][3];
sparseArray[0][0]=11;
sparseArray[0][1]=11;
sparseArray[0][2]=sum;
int count=0;
for(int i=0;i<11;i++) {
for(int j=0;j<11;j++) {
if(array1[i][j] > 0) {
count++;
sparseArray[count][0]=i;
sparseArray[count][1]=j;
sparseArray[count][2]=array1[i][j];
}
}
}
for(int i=0;i<sum+1;i++) {
for(int j=0;j<3;j++) {
System.out.printf("%d\t",sparseArray[i][j]);
}
System.out.println();
}
//转回二维数组
int array2[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
/*
* for(int i=1;i<sparseArray.length;i++) { for(int j=1;j<3;j++) {
* array2[sparseArray[i][0]][sparseArray[i][1]]=sparseArray[i][j]; } }
*
* for(int[] i:array2) { for(int j:i) { System.out.printf("%d\t",j); }
* System.out.println(); }
*/
//输出磁盘
File f = new File("E:\\JAVA\\test\\sparseArray1.data");
FileWriter fw = null;
try {
fw = new FileWriter(f);
for(int i=0;i<sparseArray.length;i++) {
for(int j=0;j<3;j++) {
fw.write(sparseArray[i][j]+"\t");
}
fw.write("\r\n");
}
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null != fw) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//读取磁盘信息
File rf = new File("E:\\\\JAVA\\\\test\\\\sparseArray1.data");
BufferedReader br = null;
FileReader f1 = null;
try {
f1 = new FileReader(rf);
br = new BufferedReader(f1);
int si = 0;
//用作读取的数据暂存,不知会不会有问题,希望有大拿指点
StringBuilder ab = new StringBuilder();
//接受读取数据,重要标记,一个br.readLine()一行数据,用来接收当前读取数据
String sl ;
while(null != (sl=br.readLine())) {
System.out.println("33333");
ab.append(sl);
ab.append("\r\n");
si+=1;
}
System.out.println("行数=="+si);
int[][] sparseArray2 = new int[si][3];
int ti = 0;
String[] s1 = ab.toString().split("\\r\\n");
for(int i=0;i<s1.length;i++) {
String[] s2 = s1[i].split("\t");
for(int j=0;j<s2.length;j++) {
sparseArray2[ti][j]=Integer.parseInt(s2[j]);
}
ti+=1;
}
//打印读取的稀疏数组
System.out.println("条数=="+sparseArray2.length);
System.out.println("11111111111");
for(int i=0;i<sparseArray2.length;i++) {
for(int j=0;j<3;j++) {
System.out.printf("%d\t",sparseArray2[i][j]);
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null != f1) {
try {
f1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}