二维数组与稀疏数组相互转换,存入磁盘和从磁盘中读取
public class SparseArray {
public static void main(String[] args) {
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
System.out.println("输出数组chessArr1:");
for (int[] arr : chessArr1) {
for (int data : arr) {
System.out.print(data + "\t\t");
}
System.out.println();
}
System.out.println("----------------------");
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
System.out.println("非0数据的个数为:" + sum);
System.out.println("----------------------");
int sparseArr[][] = new int[sum + 1][3];
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
int count = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
System.out.println("得到的稀疏数组为:");
for (int i = 0; i < sparseArr.length; i++) {
for (int j = 0; j < sparseArr[i].length; j++) {
System.out.print(sparseArr[i][j] + "\t\t");
}
System.out.println();
}
System.out.println("----------------------");
int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1; i < sparseArr.length; i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println("输出数组chessArr2:");
for (int[] arr : chessArr2) {
for (int data : arr) {
System.out.print(data + "\t\t");
}
System.out.println();
}
File file = new File("sparseArr.txt");
FileWriter fw = null;
try {
fw = new FileWriter(file);
for (int[] ints:sparseArr) {
for (int j = 0; j < ints.length-1 ; j++) {
fw.write(ints[j] + ",");
}
fw.write(ints[sparseArr[0].length-1] + "");
fw.write("\n");
fw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fw!=null){
try {
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
BufferedReader br = null;
int[][] newArr = null;
try {
br = new BufferedReader(new FileReader("sparseArr.txt"));
List<String> list = new ArrayList<>();
String line;
while ((line = br.readLine()) !=null){
list.add(line);
}
int row = list.size();
int col = list.get(0).split("\\,").length;
newArr = new int[row][col];
int rst = 0;
for(String s: list){
String[] str = s.split("\\,");
for(int i=0;i<str.length;i++){
newArr[rst][i] = Integer.parseInt(str[i]);
}
rst++;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
System.out.println("还原后的稀疏数组:");
for (int i = 0; i < newArr.length; i++) {
for (int j = 0; j < newArr[i].length; j++) {
System.out.print(newArr[i][j] + "\t\t");
}
System.out.println();
}
}
}