1、将数组包保存到磁盘文件中:
private static void intDataToFileOut(int[][] sparseArray, File file) {
FileWriter out = null;
try {
out = new FileWriter(file);
//二维数组按行存入到文件中
for (int i = 0; i < sparseArray.length; i++) {
for (int j = 0; j < sparseArray.length; j++) {
//将每个元素转换为字符串
String content = String.valueOf(sparseArray[i][j]) + "";
out.write(content + "\t");
}
out.write("\r\n");
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
上述代码中将二维数组sparseArray通过循环遍历写入到文件中。
2、从文件中读取数组:
private static int[][] getSparseArrayFromFile(){
//将稀疏矩阵从文件中读取出来
BufferedReader bufferedReader = null;
//为保存的数组分配空间
int[][] datas = new int[11][11];;
try {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(new File("F:\\data.txt")));
bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
int i=0;
//按行读取
while((line = bufferedReader.readLine() )!= null){
if(null != line){
//将按行读取的字符串按空格分割,得到一个string数组
String[] strings = line.split("\\t");
//依次转换为int类型存入到分配好空间的数组中
for(int k = 0;k<strings.length;k++){
datas[i][k] = Integer.valueOf(strings[k]);
}
//行数加1
i++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//返回读取的二维数组
return datas;
}
3、通过测试代码检验是否正确:
public static void main(String[] args) {
//1、先定义一个二维数组
int[][] chessArray;
chessArray = new int[11][11];
chessArray[1][2] = 1;
chessArray[2][3] = 2;
//2、将二维数组存入文件中
File file = new File("F:\\data.txt");
try {
SparseArray.intDataToFileOut(sparseArray, file);
} catch (Exception e) {
e.printStackTrace();
}
//3、从文件中读取数组
int[][] datas = getSparseArrayFromFile();
for (int[] row : datas) {
for (int item : row) {
System.out.printf("%d\t", item);
}
System.out.println();
}
}
在F盘下找到该文件打开:
读取数组后在控制台显示结果: